Building Your Own AI Infrastructure
From Bare Metal to Production AI Inference
An engineering journey from silicon and operating systems to the infrastructure that turns model weights into useful intelligence.
By Matthew Conran · Engineering architecture series · Editorial draft for author approval
Conceptual request and model-loading paths, not a physical wiring diagram. Model weights are normally loaded before serving; storage is not necessarily accessed for every token.
Start with a Linux host, adequate RAM, storage and a supported accelerator or CPU-only runtime.
Follow the request through the network, operating system, runtime, memory and compute layers.
Measure latency, throughput, memory pressure, reliability and security before scaling.
Explore the infrastructure stack
Select a layer to inspect its engineering role.
Physical infrastructure
CPU, RAM, PCIe and NVMe provide the host resources for model loading and execution. Accelerator memory capacity constrains model size and concurrent inference.
Inspect: Available memory, PCIe topology, storage capacity and power budget.
Start small. Scale deliberately.
Single-server AI lab
Linux, a local model runtime such as Ollama, and a supported GPU if available. CPU inference is also possible for suitable models. Start with a local API and measure resource usage.
Why build your own AI infrastructure?
Running a model is only one part of building an AI system. The operating system manages processes and memory; the runtime schedules inference; the network carries requests; and the accelerator executes numerical operations. Understanding these boundaries makes it possible to diagnose a slow response instead of simply purchasing more compute.
Private deployment can offer greater control over data placement, model selection and operational policies. It also transfers responsibility for patching, access control, capacity planning and recovery to the operator. Local hosting alone does not guarantee security or lower cost.
Explore the engineering roadmap
Physical hardware → Linux → virtualisation → networking → GPU acceleration → inference → retrieval and agents → security and observability → production operations.
The series introduces technologies progressively. Kubernetes, RDMA, distributed GPU communication and vector databases are optional components selected according to workload requirements, not prerequisites for a first local model.
Inside the AI Compute Server
Before a model generates its first token, a physical system must move billions of parameters from storage into memory, prepare an execution environment and deliver computation to the accelerator. Understanding these boundaries is the foundation of reliable AI infrastructure engineering.
Follow the model from storage to compute
CPU — host orchestration
The CPU handles operating-system services, tokenisation in many runtimes, request scheduling and accelerator command submission. CPU-only inference is also possible, usually with different performance characteristics.
Compute is only one part of the system
GPU execution units accelerate matrix operations, but the model must also access weights and intermediate tensors. During autoregressive decoding, memory bandwidth can become a dominant constraint, particularly at small batch sizes. Prefill often exposes different compute and memory bottlenecks. Neither peak FLOPS nor VRAM capacity alone predicts serving throughput.
Memory capacity and locality
System RAM supports the operating system, model loading, preprocessing and CPU execution. Dedicated GPU memory stores accelerator-resident weights, activations and attention caches. Quantisation reduces weight storage, but runtime metadata, temporary buffers and KV cache still consume memory. On multi-socket hosts, CPU affinity and NUMA placement can influence transfer latency and available bandwidth.
PCIe and persistent storage
PCIe connects devices to the host. A GPU operating at a narrower negotiated link may experience slower host-device transfers. NVMe storage influences cold model loading and dataset access, but a fully resident model does not normally reload its weights from disk for every generated token. Direct storage-to-GPU paths require compatible hardware and software and are not assumed here.
Estimate model weight storage
16.00 GB / 14.90 GiB
Ideal packed weight storage only: parameters × bits ÷ 8. Excludes quantisation metadata, KV cache, activations, allocator overhead and runtime workspace. This is not a GPU purchasing or fit guarantee.
Discover the physical server
lscpu free -h lsblk -o NAME,SIZE,TYPE,MODEL lspci -nn numactl --hardware nvidia-smi nvidia-smi topo -m
These read-only commands inspect CPU topology, memory, storage, PCIe devices and NVIDIA GPU connectivity. The numactl utility and NVIDIA drivers must be installed for their respective commands. Compare the observed topology with the intended deployment before selecting a runtime.
Why might a model fail to load even when its theoretical weight size fits in VRAM?
Weight storage is only one allocation. The runtime may also need KV cache, activations, temporary workspaces, quantisation metadata and allocator reserves. Inspect actual free device memory and runtime settings before changing hardware.
Original conceptual engineering illustration and educational estimates. Hardware behaviour depends on the platform, model and runtime. Next: PAIES-03 — Linux kernel architecture.
Linux: The Operating System Beneath AI
AI inference is not simply a GPU executing a neural network. A Linux host coordinates processes, memory mappings, storage, network sockets and accelerator access. Understanding these mechanisms makes it possible to distinguish a slow model from a starved host, a misplaced NUMA allocation or an exhausted memory subsystem.
From user space to physical hardware
AI application
The inference server accepts requests, tokenises input and schedules model execution through its runtime.
Processes, threads and scheduling
Linux schedules runnable threads onto logical CPUs. Normal scheduling on modern kernels uses fair scheduling mechanisms, including EEVDF on newer releases. Inference servers may maintain separate network, tokenisation and execution threads. CPU affinity can reduce migration, but overly restrictive pinning can create contention. Cgroup CPU quotas can throttle a container even when the host appears idle.
Virtual memory and model loading
Each process sees a virtual address space. Page tables translate virtual addresses to physical memory, and the TLB caches translations. Model files may be memory-mapped; first access can trigger page faults and storage reads. File-backed pages may be reclaimed, while anonymous allocations may be swapped if configured. GPU VRAM is a distinct resource; available host RAM does not guarantee a model fits on the GPU.
NUMA and locality
On multi-socket systems, memory attached to a local NUMA node can have lower access latency than remote memory. PCIe devices also have topology-dependent locality. Aligning CPU workers, host buffers and accelerator placement can help, but should be validated with measurements. A single-socket system may still expose multiple NUMA nodes.
System calls and GPU execution
Applications enter the kernel through interfaces such as read, mmap, epoll and ioctl. CUDA libraries and the NVIDIA driver coordinate memory and GPU work submission. GPU kernels execute on the accelerator, not as ordinary Linux CPU threads. DMA can move data without the CPU copying each byte; an IOMMU may provide device address translation and isolation.
Isolation and resource governance
Namespaces isolate selected views of system resources, while cgroups account for and constrain resource consumption. Containers share the host kernel. GPU access also depends on device permissions, runtime integration and compatible drivers. Isolation is not equivalent to a dedicated virtual machine security boundary.
Estimate host memory access latency
90 ns
150 ns
Illustrative weighted average only: ignores caches, bandwidth, queueing and concurrency. Not a benchmark or prediction of token latency.
Inspect the host-side execution path
Simplified example; real serving engines overlap stages and batch multiple requests.
Read-only host diagnostics
uname -r lscpu free -h vmstat 1 5 cat /proc/pressure/memory numactl --hardware lspci -nn nvidia-smi nvidia-smi topo -m cat /proc/self/cgroup
Inspect CPU topology, memory availability, pressure stalls, NUMA layout and accelerator connectivity. numactl, lspci and NVIDIA utilities require the relevant packages or drivers; pressure metrics depend on kernel support. Run on the Linux AI host, not the browser.
How to interpret memory pressure
Check available memory, sustained swap activity and pressure stall metrics together. A low free-memory value alone is not evidence of exhaustion because Linux uses RAM for reclaimable caches.
How to investigate GPU underutilisation
Correlate GPU utilisation and memory use with CPU saturation, cgroup throttling, request batching, storage latency and model-serving metrics. Low utilisation alone does not identify a fault.
GPU utilisation is low, but the container CPU quota is exhausted. What should you investigate first?
Select an investigation.
Network Insight · Original educational architecture and illustrative simulation · PAIES-03 V1
Will your AI model fit inside GPU memory?
Design a private inference server by separating model weights, attention cache and runtime overhead. A model that fits at startup can still run out of memory when requests grow longer or concurrency increases.
01 — Configure your deployment
02 — Memory budget inspector
Aggregate capacity is a necessary but insufficient condition. Tensor parallelism, per-device allocations, quantisation metadata, allocator fragmentation, activations and communication buffers can change feasibility. This is not a hardware benchmark.
03 — Understand the calculation
Parameters × weight bits ÷ 8. This ideal packed estimate excludes format metadata and mixed-precision tensors.
2 × layers × KV heads × head dimension × bytes per element × cached tokens × concurrent requests. Assumes conventional full attention and equal sequence lengths; sliding windows, prefix sharing and specialised architectures may differ.
Reserve per GPU × GPU count. This is a configurable allowance, not a measured runtime allocation. All results use GiB (2³⁰ bytes).
04 — Engineering incident
A model starts successfully but fails under simultaneous long-context requests. Which resource should you investigate first?
Select an answer.
Try the long-context stress preset, then reduce concurrency or context length. Observe the change in estimated cache demand before considering additional GPUs.
05 — Validate on real Linux infrastructure
nvidia-smi --query-gpu=name,memory.total,memory.used --format=csv nvidia-smi topo -m lspci -nn | grep -Ei 'VGA|3D|NVIDIA' free -h lsblk -o NAME,SIZE,TYPE,MODEL
Use the actual model configuration to obtain layer count, KV head count and head dimension. Measure peak memory under representative load using your serving runtime metrics. NVIDIA commands require an installed compatible driver.
Original educational engineering model · Network Insight · Illustrative estimates, not deployment guarantees.
Inside the Linux AI execution path
Follow a conceptual inference request from userspace to GPU execution. Change NUMA locality, transfer size, PCIe throughput and failure conditions to investigate the infrastructure beneath model serving.
01 / Configure the system
02 / Animated execution journey
Select a stage or run the journey.
Animation timing is educational, not proportional to measured latency. GPU runtime calls do not necessarily require a system call for every operation.
03 / Engineering telemetry
Event console
Ready.
04 / Diagnostic workstation
lscpu numactl --hardware numastat -p PID
Check CPU placement and memory distribution. Replace PID with the serving process ID.
lspci -nn nvidia-smi nvidia-smi topo -m lspci -vv -s BDF
Replace BDF with the device address; compare negotiated link width and speed with capabilities.
vmstat 1 pidstat -u -r -w 1 journalctl -k -b
Inspect run queues, major faults, context switches and kernel driver messages. Some tools require additional packages or permissions.
05 / Troubleshooting challenge
A serving process runs on NUMA node 0, but its host buffers are predominantly allocated on node 1. GPU visibility is healthy. What should you investigate first?
Network Insight • Original conceptual engineering simulation. No live hardware access or benchmark claims. Editorial and technical guidance.
Linux Virtualisation, Containers and Infrastructure Isolation
A private AI platform is not simply a GPU attached to a Linux server. It is a collection of execution environments, resource boundaries and data paths that must remain predictable when multiple workloads compete for the same physical infrastructure.
Containers share the host kernel. Namespaces isolate views of resources; cgroups account for and constrain supported resource usage. GPU access requires compatible host drivers and runtime configuration.
Conceptual execution layers, not a literal packet or instruction trace.01 / KVM and QEMU: a separate operating system boundary
KVM exposes hardware-assisted virtualisation through the Linux kernel. QEMU provides a userspace virtual machine monitor and device model, using KVM acceleration when available. A guest operating system runs its own kernel and applications, while virtual CPUs are scheduled as host threads. Guest physical addresses are translated to host memory using hardware-assisted second-stage translation on supported processors.
For AI infrastructure, this boundary is useful when teams require separate operating systems, independent kernel configurations or stronger workload separation than a shared-kernel container provides. It also introduces additional operational concerns: guest memory allocation, virtual CPU placement, NUMA locality and virtual device performance. Virtualisation overhead is workload-dependent; it cannot be inferred from the number of layers alone.
02 / VirtIO and virtual networking
VirtIO defines paravirtualised device interfaces, allowing a guest driver and a host backend to exchange work through shared queues rather than relying entirely on emulated legacy devices. Virtio-net and virtio-blk are common examples. A vhost backend may accelerate parts of the data path. These mechanisms reduce overhead but do not eliminate host scheduling, queueing or memory costs.
A typical virtual machine network connects a guest virtio-net interface to a host TAP interface and then to a Linux bridge or Open vSwitch. Open vSwitch provides programmable forwarding and can support VLANs, tunnels and policy depending on configuration. A container often uses a veth pair and a bridge instead, although host networking, macvlan and other CNI implementations provide alternative paths. NAT is optional, not an inherent requirement of virtual networking.
Guest NIC → VirtIO queues → host backend / TAP → virtual switch → physical NIC.
Application socket → shared kernel network stack → veth → bridge or CNI datapath → uplink.
03 / Containers: isolation without a separate kernel
A container is a collection of Linux processes running with configured isolation and resource controls. PID, mount, network, IPC, UTS and user namespaces can provide separate views of system resources. Cgroups v2 provide hierarchical accounting and controls for resources such as CPU, memory and I/O. A container image supplies userspace files and dependencies, not an independent kernel.
Docker packages these primitives into a developer and operational workflow. An OCI-compatible runtime establishes the process environment, mounts the filesystem and applies configured restrictions. For AI serving, the image can contain Python, inference libraries and model-serving software while model weights are mounted from persistent storage. Keeping weights separate from images can simplify upgrades and avoid repeatedly transferring large model files.
Isolation is not automatic security. Avoid privileged containers, unnecessary capabilities and unrestricted host mounts. Apply appropriate seccomp, mandatory access controls and non-root execution where supported. GPU device access and the shared kernel remain part of the trust boundary.
04 / GPU access: containers versus PCIe passthrough
GPU-enabled containers normally use the host NVIDIA kernel driver. NVIDIA Container Toolkit can configure access to GPU devices and compatible driver libraries. CUDA userspace libraries and the host driver must satisfy compatibility requirements. Exposing a GPU to a container does not automatically impose a VRAM quota; CPU and memory cgroup limits do not generally limit GPU memory allocations.
For a virtual machine, PCIe passthrough can assign a physical GPU to a guest using VFIO and an enabled IOMMU. The IOMMU constrains device DMA mappings; device isolation depends on platform topology and IOMMU groups. The guest normally loads its own GPU driver. A passed-through device is typically dedicated to that guest while assigned, unless supported mediated or partitioning technology is explicitly configured. GPU reset behaviour, firmware and platform support must be verified before deployment.
05 / Resource placement and production decisions
On a multi-socket server, a GPU may be attached to a PCIe root complex associated with one NUMA node. Placing CPU workers and host memory near that device can reduce remote memory traffic. CPU pinning alone is insufficient if memory allocation remains remote. Benchmark the complete workload, including tokenisation, host-to-device transfers, batching and network traffic, before selecting placement policies.
Start with containers and explicit GPU access. Keep model storage persistent and expose only necessary service ports.
Consider VMs with separately managed kernels, network policies and dedicated GPU assignment where supported.
Introduce orchestration when scheduling, recovery and multi-node operations justify its complexity. Kubernetes is not required for a single inference server.
Engineering inspection console
Read-only diagnostic examples for an appropriately configured Linux host. Some commands require optional packages, permissions or installed runtimes.
lscpu numactl --hardware ls -l /dev/kvm lsns stat -fc %T /sys/fs/cgroup ip -br link bridge link ovs-vsctl show lspci -nnk nvidia-smi topo -m docker info virsh list --all
Compare the CPU and NUMA topology with GPU placement. Inspect virtual interfaces and switch membership before investigating application-level latency. Missing commands or devices are not by themselves proof of a fault; they may indicate an uninstalled or unused component.
Engineering checkpoint
An inference container reaches its configured host RAM limit, but GPU memory usage remains high. Which explanation is most accurate?
Select an explanation.
Engineering perspective: Choose the isolation boundary according to trust, hardware ownership and operational requirements, then measure the resulting data path. A more complex architecture is not automatically a faster or safer one.
Further technical reading: Linux KVM documentation · cgroups v2 · Open vSwitch · NVIDIA Container Toolkit.
Inside the virtual packet journey
Follow a request from a virtual workload to the physical network. Compare the guest kernel and VirtIO path of a KVM virtual machine with the shared-kernel veth path of a Linux container. Inject a fault and identify the first failing boundary.
01 — Configure your virtual infrastructure
Outbound IPv4 packet, established neighbor entries, no fragmentation (DF set). Baseline path MTU 9000 bytes; injected mismatch reduces uplink MTU to 1400 bytes. This is a conceptual model, not a live hypervisor.
Engineering event console
Ready.
02 — Understand the isolation boundary
Virtual machines: KVM provides hardware-assisted CPU and memory virtualization. QEMU supplies the virtual machine device model. A guest VirtIO network driver places buffer descriptors into virtqueues; a host backend such as vhost-net can process these buffers and connect the traffic to a TAP interface. A Linux bridge or Open vSwitch forwards Ethernet frames toward the uplink.
Containers: A container shares the host Linux kernel. Network namespaces isolate interfaces, routing tables and network configuration. A veth pair connects the workload namespace to the host forwarding domain. Cgroups regulate resource consumption; they do not themselves create network isolation. Firewall and NAT processing depend on the configured forwarding path.
GPU passthrough: VFIO and an IOMMU can assign a PCIe device to a guest while restricting DMA mappings. GPU passthrough does not automatically bypass the virtual network. A GPU data transfer and an Ethernet packet are separate journeys unless an explicitly configured mechanism such as GPUDirect RDMA connects them.
Inspect GPU assignment and isolation
Check IOMMU groups, the bound PCI driver, guest device visibility and GPU runtime compatibility. A container using NVIDIA Container Toolkit normally accesses host GPU device interfaces through the host driver rather than owning a PCIe device through VFIO.
lspci -nnk find /sys/kernel/iommu_groups/ -type l nvidia-smi
03 — Engineering diagnostic toolkit
Run the appropriate read-only commands on your own authorized Linux lab. Some require installed tools or elevated privileges.
ip -br link ip route ip -s link bridge link bridge fdb show ip netns list virsh domiflist <vm-name> ovs-vsctl show sudo nft list ruleset sudo tcpdump -ni <interface> -c 20
Compare captures at the guest or container interface, host TAP or veth, switch and physical uplink. The first point where a packet disappears narrows the failure domain. Docker-managed namespaces may not appear in ip netns list; inspect the container PID and use authorized namespace tooling when required.
04 — Troubleshooting challenge
A 1500-byte IPv4 packet with DF set reaches the virtual switch, but the uplink supports only 1400 bytes. Which action addresses the underlying mismatch?
Choose an action, then reproduce the failure using the simulator.
Original educational simulation · Network Insight · Model assumptions are illustrative; actual packet paths vary by hypervisor, offload, firewall and network configuration.
AI Data Centre Networking and Distributed Fabrics
A GPU cluster is only as useful as its ability to move data between accelerators, storage and applications. The network becomes part of the computation itself when a model spans multiple servers.
Follow the data across the fabric
An inference request crosses the routed fabric from the gateway to GPU B. The return path need not use the same spine.
Conceptual paths, not live routing telemetry. The highlighted route is one possible path.
01 · The fabric as a computing resource
Traditional enterprise networks often optimise north–south traffic between users and applications. Distributed AI adds intense east–west traffic between compute nodes. Training can require repeated gradient exchanges; distributed inference may exchange activations or partial results. A single-GPU inference service may need neither a dedicated RDMA fabric nor a high-end switch.
Separate management, client-facing service, storage and accelerator traffic according to operational needs. Physical separation is not mandatory, but shared links require capacity planning and explicit congestion policy. A fast GPU cannot compensate for a saturated interconnect when its next operation depends on remote data.
02 · Spine–leaf architecture and capacity
Each leaf connects to every spine in a conventional two-tier Clos fabric. Servers attached to different leaves normally traverse one spine. Adding spines can increase aggregate capacity when links and forwarding resources support it. Redundant links provide alternate paths, but redundancy does not guarantee uninterrupted application execution.
Oversubscription is the ratio of aggregate server-facing bandwidth to aggregate uplink bandwidth. A leaf with eight 100 Gb/s server ports and four 100 Gb/s uplinks has a nominal 2:1 ratio. Real usable throughput depends on traffic distribution, protocol overhead and failures. Design for the expected collective communication pattern rather than port counts alone.
03 · BGP, ECMP and FRRouting
A routed fabric can use eBGP between leaf and spine switches to exchange reachability. BGP selects eligible paths; multipath configuration can install multiple equal-cost next hops into the forwarding table. ECMP commonly hashes flow headers to select a next hop, rather than distributing every packet independently.
Large AI flows can collide on the same link despite equal-cost alternatives. Flow-aware load balancing and adaptive routing may help on supported platforms, but reordering can harm some transports. FRRouting provides a practical Linux-based environment for studying BGP adjacency, route propagation and multipath forwarding before deploying a physical fabric.
04 · RDMA and RoCEv2
Remote Direct Memory Access allows a capable NIC to transfer data between registered memory regions with reduced CPU involvement in the data path. Applications still need to establish connections, register buffers and handle completions. RDMA does not mean that the CPU or operating system disappears.
RoCEv2 carries RDMA transport over UDP/IP and can traverse routed Ethernet fabrics. Congestion management is critical: ECN marking and endpoint rate control can reduce congestion; priority flow control may be used for selected traffic classes depending on the design. PFC can also propagate congestion and create head-of-line blocking. A lossless configuration is not a substitute for end-to-end testing.
05 · InfiniBand and accelerator communication
InfiniBand is a distinct switched interconnect with its own link and transport architecture and subnet management. It supports RDMA and is widely used in high-performance computing. Ethernet with RoCEv2 and InfiniBand are alternative fabric choices; neither is universally superior for every workload.
NCCL implements collective operations such as all-reduce, all-gather and reduce-scatter. It can select communication paths based on topology and available transports. Within a server, PCIe or NVLink may carry GPU traffic; across servers, network adapters and the fabric become relevant. GPUDirect RDMA can enable direct NIC access to GPU memory on compatible systems, subject to topology, driver and platform constraints.
06 · Congestion and failure domains
Microbursts can fill switch queues even when average utilisation appears modest. Collective operations can create synchronised bursts, and the slowest participant can delay the entire group. Monitor queue occupancy, ECN marks, drops, retransmissions and per-link utilisation rather than relying solely on aggregate throughput.
A spine failure reduces available path capacity. BGP convergence and forwarding updates can restore reachability, but an active transport or collective may still time out. Test failure recovery at application level, including job restart and checkpoint recovery where appropriate.
07 · From private server to production fabric
Start with ordinary Ethernet for a single inference server. Measure application latency and throughput before adding complexity. When moving to multiple GPU nodes, establish whether the workload actually requires model parallelism or simply independent replicas behind a load balancer. Replication can avoid cross-node GPU communication for models that fit on one server.
For distributed models, validate NIC placement, PCIe locality, GPU topology, MTU consistency, routing and transport compatibility. Benchmark both isolated links and full application workloads. Establish a baseline, introduce one change at a time and record the impact on tail latency and throughput.
Engineering capacity calculator
Estimate nominal leaf oversubscription. This is a line-rate calculation, not an application throughput prediction.
Practical Linux fabric inspection
Run these read-only commands on an appropriate Linux host. FRRouting, RDMA and NVIDIA tools must be installed where applicable.
ip -br link ip route show ip -s link ethtool <interface> ethtool -S <interface> vtysh -c 'show bgp summary' vtysh -c 'show ip route' rdma link show ibv_devinfo nvidia-smi topo -m
Correlate interface counters with routing state and GPU locality. Replace the interface placeholder with the actual device name. Driver-specific counter names vary.
Engineering checkpoint
Two GPU nodes communicate across a fabric with four equal-cost paths, but one link is saturated. What should you investigate first?
Select an answer.
Continue with PAIES-15, the interactive AI network fabric simulator. All examples are educational and require validation against the actual platform.
Inside the AI data centre fabric
Follow a flow across a two-spine, two-leaf routed fabric. Inspect equal-cost next hops, change the flow identifier, introduce a link failure and examine the difference between routing convergence and transport congestion.
01 / Configure the experiment
02 / Live fabric topology
Ready.
Queue growth = max(0, offered rate − effective service rate), before congestion control or drops. This is a fluid-rate teaching model, not measured throughput.
03 / Leaf A routing inspection
Destination: 10.20.0.0/24, originated by Leaf B. The table represents a simplified post-convergence BGP multipath state, assuming compatible attributes and multipath-relax configuration where required.
| Next hop | AS path | State |
|---|
Event console
04 / Engineering interpretation
ECMP: A flow normally stays on one selected path to avoid packet reordering. Multiple flows can distribute across uplinks, but a single flow does not automatically receive the sum of their capacities. This lab uses flow ID modulo eligible paths as a deliberately simplified hash.
RoCEv2: RDMA traffic is carried over UDP/IP. ECN marking and congestion notification can help endpoints reduce sending rates; PFC may be used for selected priorities but can propagate congestion. Neither mechanism creates extra bandwidth. GPUDirect RDMA can avoid host-memory staging when supported by the platform.
InfiniBand: A separate fabric technology with its own subnet management, routing and link-level flow control. This Ethernet/IP lab does not simulate InfiniBand forwarding.
Failure recovery: A physical link failure may trigger interface events, BFD or BGP session loss. Real convergence takes time and may lose in-flight packets. The route table here immediately represents the converged state; no BGP timers or actual protocol packets are simulated.
MTU: The mismatch scenario assumes a 1500-byte IP MTU on the selected path and a non-fragmentable IP packet. A 9000-byte packet fails in this model; real TCP may adapt via path MTU discovery, while RDMA configuration requires consistent supported MTUs.
05 / Diagnostic field guide
ip -br link ip -s link ip route show 10.20.0.0/24 vtysh -c 'show bgp ipv4 unicast 10.20.0.0/24' vtysh -c 'show bgp summary' ethtool -S eth0 rdma link show nvidia-smi topo -m
Read-only examples for a Linux/FRRouting host; interface names, permissions and installed tools vary. Switch queue and ECN counters are vendor-specific.
Engineering challenge
A GPU collective is slow, but both BGP next hops remain available. Which experiment best distinguishes congestion from a routing outage?
Suggested experiments
Run flow 0 and flow 1 with a healthy fabric. Disable the Spine 1 uplink and repeat. Next select congestion, flow 0, and 80 Gb/s on a 100 Gb/s link. Compare route availability and queue growth. Finally choose MTU mismatch and 9000-byte packets.
Network Insight · Original educational simulation · Illustrative topology and assumptions, not a production benchmark. Legal & Editorial Centre
NVIDIA GPU Architecture, CUDA and Acceleration
An AI accelerator is not simply a faster CPU. Its architecture is designed to execute large numbers of parallel operations while moving tensors through a carefully organised hierarchy of memory. Understanding that movement is essential to designing a private AI platform.
Follow the computation
Model weights are transferred from host memory to device memory. Storage reads and host-to-device copies are distinct operations.
Conceptual diagram: exact cache, memory and interconnect organisation varies by GPU architecture. Animated lines indicate logical data movement, not measured timing.
01 — The GPU as a parallel execution engine
A CPU is optimised for general-purpose control flow, low-latency execution and complex operating system tasks. A GPU instead dedicates substantial silicon resources to throughput. CUDA exposes this capability through kernels: functions launched by the host and executed by many GPU threads. The host still coordinates the application, allocates memory and submits work through the CUDA runtime and driver.
CUDA organises threads into blocks and blocks into grids. Blocks are assigned to streaming multiprocessors (SMs), where threads execute in groups called warps, normally containing 32 threads on NVIDIA CUDA GPUs. When threads in a warp take different control-flow paths, execution efficiency can decrease. Occupancy describes the proportion of supported resident warps that are active; higher occupancy can help hide latency, but does not guarantee faster execution.
02 — Tensor Cores and numerical precision
Transformer inference repeatedly performs matrix operations in attention and feed-forward layers. Tensor Cores accelerate supported matrix multiply-accumulate operations, while other execution units handle general arithmetic, address calculations and additional operations. Libraries such as cuBLAS and specialised attention kernels select implementations based on tensor dimensions, data types and hardware capabilities.
FP32, TF32, FP16, BF16, FP8 and integer formats have different numerical properties and hardware support. Quantised model weights can reduce storage and memory traffic, but may require dequantisation or specialised kernels. A smaller numerical format is not automatically faster: kernel availability, alignment, accumulation precision and model quality must all be evaluated. Support for specific formats varies across GPU generations.
03 — Memory hierarchy and HBM
Registers hold thread-local values; shared memory enables cooperation between threads in a block. Caches reduce repeated trips to device memory. High-bandwidth memory (HBM), where present, stores model weights, activations and KV cache. Other GPU products use GDDR memory instead. Capacity determines what can fit, while bandwidth determines how rapidly data can be supplied to computation.
During autoregressive decoding, a small batch may repeatedly stream substantial portions of the model weights for each generated token. This can make memory bandwidth a stronger constraint than peak arithmetic throughput. Larger batches can improve reuse but increase memory pressure and queueing latency. Prefill often offers greater parallelism, although the actual bottleneck depends on sequence length, batch size and kernel implementation.
Idealised weight-streaming bandwidth ceiling
Decimal GB. Assumes a full weight scan per iteration at peak bandwidth, with no reuse, overhead, KV traffic or compute limit. This is not a token throughput prediction or a GPU fit test.
04 — CUDA software and the Linux driver boundary
The NVIDIA kernel driver manages access to the accelerator and works with userspace driver libraries. The CUDA runtime provides application-facing APIs for allocation, copies, streams and kernel launches. Frameworks such as PyTorch sit above this stack. A container packages userspace dependencies, but normally shares the host kernel and relies on a compatible host GPU driver. Installing a CUDA toolkit inside a container does not replace that driver.
CUDA streams permit ordered execution within a stream and potential overlap between independent streams. Asynchronous copies and computation can overlap when hardware, memory allocation and dependencies permit it. Synchronisation points may eliminate that overlap, so profiling should precede optimisation. Pinned host memory can improve transfers, but excessive pinning reduces the memory available to the operating system.
05 — PCIe, NVLink and NVSwitch
PCIe connects accelerators to the host and may also support peer-to-peer communication, depending on platform topology and configuration. NVLink provides high-bandwidth GPU interconnects on supported systems. NVSwitch enables switched NVLink connectivity on supported platforms. Neither should be assumed to exist on every NVIDIA GPU or server.
When a model exceeds the capacity of a single GPU, tensor parallelism can partition operations across accelerators, requiring communication between layers. Pipeline parallelism divides model stages, introducing scheduling and pipeline considerations. Data parallelism replicates models for independent work or training. These approaches solve different problems; adding GPUs does not automatically improve latency for a single request.
06 — NCCL and distributed computation
NCCL provides GPU collective communication primitives such as all-reduce, all-gather and reduce-scatter. Its transport selection depends on the topology and available network interfaces. Within a server, communication may use NVLink or PCIe. Across servers, supported RDMA transports can reduce host involvement; GPUDirect RDMA can enable direct access to GPU memory by compatible network devices.
Collective performance depends on message size, topology, bandwidth, latency and synchronisation. A slow participant can delay an entire collective. Investigate GPU utilisation alongside interconnect counters and collective timings before attributing a distributed performance problem to insufficient GPU compute.
07 — Isolation, MIG and production scheduling
Multi-Instance GPU (MIG) on supported devices partitions GPU resources into hardware-backed instances with defined compute and memory resources. This differs from time-slicing, which shares execution time without equivalent hardware resource isolation. MIG profiles and supported features vary by GPU. Partitioning can improve predictability for smaller workloads but may prevent a large model from fitting into an individual instance.
In Kubernetes, device plugins advertise GPU resources to the scheduler; the NVIDIA GPU Operator can automate components of the GPU software stack. Scheduling a GPU does not guarantee optimal CPU NUMA placement, storage performance or network affinity. Production designs must consider those resources together, as well as workload admission and failure recovery.
08 — Practical engineering inspection
nvidia-smi nvidia-smi -L nvidia-smi topo -m nvidia-smi --query-gpu=name,memory.total,memory.used,utilization.gpu,temperature.gpu --format=csv lspci -nn | grep -i nvidia numactl --hardware nvcc --version
These read-only commands require the relevant tools to be installed. The CUDA version displayed by nvidia-smi indicates driver-supported CUDA compatibility, not necessarily the installed toolkit version. Use Nsight Systems or Nsight Compute for deeper profiling when available.
A decoding bottleneck
A model fits in GPU memory, but single-request decoding is slow and profiling shows high memory bandwidth utilisation with low arithmetic utilisation. What should you investigate first?
Select an engineering diagnosis.
Engineering perspective
Design the accelerator platform around the model and service objectives, not a single peak performance number. Establish memory fit, measure time to first token and inter-token latency, then test throughput under realistic concurrency. Inspect the GPU, host, network and serving runtime as one system. The next interactive lab, PAIES-16, investigates these relationships through simplified computation and communication models.
Further reading: CUDA programming guide · NCCL documentation · MIG user guide. Original educational explanation; no vendor endorsement implied. Editorial and legal information.
Inside the GPU: from CUDA launch to distributed computation
A GPU is not simply a faster CPU. Its performance depends on parallel execution, data reuse, memory traffic and communication. Configure a conceptual accelerated workload, follow its execution and identify which resource limits progress.
01 / Configure your accelerated workload
Ready to launch.
02 / GPU execution architecture
Select any component to inspect its role. Highlighting follows the simulated execution, not a physical GPU floorplan.
03 / Streaming multiprocessor — warp inspector
Each tile represents a conceptual 32-thread warp, not an actual occupancy measurement. Real scheduling depends on architecture, registers, shared memory and instruction dependencies.
04 / Roofline and collective telemetry
Compute time
Memory time
Collective time
05 / Engineering event console
06 / Engineering investigations
Experiment A — Why decode can be memory bound
Choose decode, one GPU and healthy workload. Increase compute capacity without changing HBM bandwidth. Observe whether the estimated kernel time changes. Then increase HBM bandwidth. Low arithmetic intensity often limits decode throughput, although batching and model architecture can change this balance.
Experiment B — When faster GPUs cannot fix communication
Choose distributed tensor computation, four GPUs and a constrained link. Compare the collective estimate with kernel time. Inject transport degradation, then increase link capacity. The model uses a simplified ring all-reduce; real NCCL can choose different algorithms and topologies.
Experiment C — Diagnose a memory allocation failure
Inject allocation failure and run the journey. The workload stops before kernel execution. In production, inspect available memory, other processes, allocator behaviour, model weights and KV cache. Increasing link speed cannot resolve an allocation failure.
07 / Diagnostic command reference
nvidia-smi nvidia-smi topo -m nvidia-smi --query-gpu=name,memory.total,memory.used,utilization.gpu --format=csv nvidia-smi -q -d MEMORY lspci -nn | grep -i nvidia # If installed: inspect a CUDA workload with Nsight Systems nsys profile -o gpu_trace ./your_cuda_application # If installed: run NCCL tests with a suitable multi-GPU setup ./build/all_reduce_perf -b 8M -e 128M -f 2 -g 2
These are inspection and profiling examples for a suitably configured Linux system. Profiling and collective tests consume resources; run them in a controlled environment.
08 / Troubleshooting checkpoint
A distributed workload spends more time in all-reduce than in its GPU kernel. Which investigation is most relevant first?
Educational simulation · Original Network Insight engineering content · No hardware access or external dependencies. Numerical estimates are illustrative, not NVIDIA product specifications or measured benchmarks.
AI Inference, Model Serving and Token Generation
A model file is not an inference service. Production AI requires a runtime that translates requests into tensor operations, manages accelerator memory and schedules competing sequences while delivering tokens within a latency budget.
From API request to streamed response
1. The serving layer is an infrastructure boundary
Clients should address a stable API rather than a GPU process directly. A gateway can authenticate callers, enforce request limits and route to a model deployment. The runtime validates generation parameters, applies the model-specific chat template and converts text to token IDs. A scheduler then decides when the sequence can enter execution. This separation makes it possible to replace a model or change accelerator placement without changing every application.
Model weights must be available to the runtime, normally from local storage or a controlled model repository. Loading weights into accelerator memory is a different operation from processing a prompt. Cold starts may include storage reads, memory allocation and kernel initialisation; warm requests can reuse resident weights. A health endpoint that responds before weights are ready is not sufficient evidence that the deployment can serve traffic.
2. Tokenisation and transformer execution
Tokenisers map text to vocabulary identifiers using model-specific rules. A token may represent a word, part of a word, punctuation or a byte sequence. The same text can produce different token counts with different tokenisers. Input limits must therefore be enforced using the actual model tokenizer, including system instructions, retrieved documents and chat history.
In a decoder-only transformer, embeddings enter successive attention and feed-forward layers. Attention combines information from permitted earlier positions, while feed-forward operations transform the hidden representation. The final projection produces logits over the vocabulary. Sampling or greedy selection chooses a token, which becomes part of the next decoding step. This is repeated until a stopping condition, output limit or cancellation is reached.
3. Prefill versus decode
Processes prompt positions together, constructs key and value tensors and produces logits for the first generated token. Long prompts increase work and can delay first-token delivery. Attention implementations and prompt lengths influence the compute and memory costs.
Typically generates one token per active sequence per iteration in conventional autoregressive serving. Existing KV entries are read and new entries appended. Weight and cache movement often dominate small-batch decoding; larger batches can improve utilisation but increase contention.
Speculative decoding can propose several tokens using a draft mechanism and verify them with the target model. It is not equivalent to independent parallel generation: accepted tokens must remain consistent with the target decoding algorithm. Benefits depend on acceptance rate, hardware and implementation.
4. KV cache is a capacity planning problem
Keys and values from previous positions can be cached so they do not need to be recomputed at every generation step. For a conventional transformer with uniform layers, the uncompressed cache estimate is two times layer count times KV head count times head dimension times bytes per element times cached tokens. Grouped-query attention can reduce KV head count compared with full multi-head attention. Model weights and KV cache may use different precisions.
Serving engines can allocate cache in blocks, reducing the need for large contiguous allocations. Prefix caching can reuse compatible prompt blocks when supported, but isolation policies and eviction matter. Actual allocations include block rounding, runtime workspaces, fragmentation and implementation-specific metadata. Tensor parallelism may shard or replicate cache depending on the model and runtime.
Estimate memory and latency
Illustrative dense 8-billion-parameter model, 32 layers, 8 KV heads, head dimension 128. No prefix sharing. Aggregate memory only; per-device placement is not modelled.
Assumptions: 2 GiB fixed illustrative runtime reserve, ideal packed weights, full prompt plus generated tokens resident for every sequence. Latency uses user-selected effective rates, not a hardware benchmark; network and sampling overhead are excluded.
5. Continuous batching and scheduling
Static batching waits for a group of requests and may waste capacity when short sequences finish before long ones. Continuous batching can admit and retire sequences between execution iterations. This improves the opportunity to share weight reads and keep accelerators busy. However, the scheduler must still account for cache capacity, prompt processing and service objectives. Chunked prefill can interleave portions of long prompts with decode work where supported.
Admission control should bound both concurrent requests and token budgets. A request with a long context can consume much more cache than a short request. Queue limits, deadlines and cancellation propagation protect the service from unbounded waiting. An overloaded gateway should return an explicit retryable response rather than silently accepting work that cannot complete.
6. Selecting a serving runtime
| Runtime | Engineering role | Deployment consideration |
|---|---|---|
| Ollama | Local model management and convenient inference API | Useful for a single-host starting point; validate model format, accelerator offload and concurrency. |
| vLLM | LLM serving with continuous batching and block-based KV management | Validate supported models, precision, parallelism and memory limits. |
| NVIDIA Triton | Inference server with configurable model backends and model repositories | LLM-specific scheduling depends on the selected backend, such as TensorRT-LLM; Triton itself is not a single LLM engine. |
Choose the runtime according to workload, supported model architecture, hardware, operational maturity and licensing. A private platform may begin with Ollama and later use vLLM for a shared service. Triton can provide a common serving interface for heterogeneous models when appropriate backends are available.
7. Production performance and observability
Time to first token measures the delay from request submission to the first delivered token. Inter-token latency measures the spacing between subsequent tokens. End-to-end latency includes queueing and response generation. Throughput should distinguish aggregate output tokens per second from per-user generation speed. Report percentile distributions under realistic arrival rates, not just averages from a single warm request.
Correlate request IDs across gateway and runtime logs. Monitor queue depth, active sequences, cache utilisation, GPU memory, accelerator utilisation, error rates and cancellation. A low GPU utilisation reading can indicate CPU tokenisation, scheduling gaps or memory stalls rather than a lack of demand. GPU memory allocation alone does not establish that compute resources are saturated.
8. Practical inspection on a private server
nvidia-smi nvidia-smi --query-gpu=name,memory.total,memory.used,utilization.gpu --format=csv # Ollama local service (if installed and running) curl --fail http://127.0.0.1:11434/api/tags # vLLM OpenAI-compatible service (if running on port 8000) curl --fail http://127.0.0.1:8000/v1/models # Inspect listening sockets ss -lntp
These are read-only inspection examples for a Linux host. Authentication may be required by the configured service. Keep unauthenticated development endpoints bound to loopback or protected by an authenticated gateway. Do not expose model-management APIs directly to the public internet.
Diagnose a latency regression
Under load, time to first token rises sharply while the rate of tokens after the first token remains stable. Which investigation should come first?
Select an investigation.
9. From local inference to a production platform
Start with one model, a bounded request size and a reproducible workload. Establish baseline latency and memory usage before introducing additional replicas or parallelism. Scale replicas for independent requests when model placement permits; use tensor or pipeline parallelism when model capacity or performance requirements justify the communication cost. Test failure recovery, readiness, rolling upgrades and model version compatibility before serving critical workloads.
Next investigation: PAIES-17 — AI Inference and KV Cache Engineering Simulator. The diagrams and estimator above are original conceptual teaching models, not measured production benchmarks.
Inside the inference engine
Follow a request from tokenisation to prefill and autoregressive decoding. Change the workload, inspect the KV cache and investigate why a model that fits in GPU memory can still fail under concurrent demand.
01 / Configure your inference server
Illustrative 8B transformer: 32 layers, 8 KV heads, head dimension 128. Fixed runtime reserve 2 GiB. Quantised weight metadata, allocator fragmentation and architecture-specific constraints are not modelled.
02 / Inspect the memory budget
Blue: weights · Gold: runtime reserve · Teal: reserved KV cache for admitted requests. Bar is capped at GPU capacity.
Inspect the KV cache formula
Bytes per token = 2 × layers × KV heads × head dimension × bytes per element. The factor of two represents keys and values. With the default architecture and 16-bit KV, this is 131,072 bytes per token (128 KiB). Admission reserves prompt plus maximum output tokens per request. Real paged allocators may allocate incrementally and use different admission policies.
03 / Execute the request journey
Illustrative token stream — request 1
Token chips are counters, not actual model-generated language. Each simulation step advances a compressed scheduling interval.
| Request | State | Generated | KV allocated |
|---|
Engineering event console
04 / Engineering investigations
Investigation A — Why does a model fit but requests queue?
Choose memory pressure, then compare weights with the cache reservation. Reduce prompt length or batch slots. A request can wait even when model weights fit, because admitting it requires additional cache capacity.
Investigation B — Continuous batching
Choose continuous batching. Observe completed requests releasing cache and queued requests entering available slots. This simplified scheduler admits new requests between decode steps; real engines may interleave chunked prefill and decode.
Investigation C — Decode bottleneck
Inject a decode bandwidth bottleneck and compare estimated completion time. Decode often depends heavily on memory traffic, but actual bottlenecks depend on batch size, hardware and model architecture.
Knowledge checkpoint
Which change directly reduces KV bytes per token without changing the model architecture?
05 / Production diagnostic field notes
nvidia-smi nvidia-smi --query-gpu=memory.used,memory.total,utilization.gpu --format=csv nvidia-smi dmon curl -s http://localhost:8000/metrics
Inspect GPU memory alongside request queue depth, time to first token, inter-token latency and cache utilisation. The metrics endpoint is an example for a locally configured serving engine; availability and metric names vary by runtime and version. Do not expose unauthenticated inference or metrics endpoints publicly.
Network Insight · Educational engineering model, not a benchmark or a live inference runtime.
Enterprise RAG, Vector Databases and AI Agents
From private model serving to a governed cognitive infrastructure: knowledge retrieval, durable orchestration and controlled tool execution.
Follow the knowledge and execution journey
Store original documents with versioned identifiers.
01 — From model serving to knowledge infrastructure
A model server exposes inference, but it does not automatically know the contents of a private document repository. Retrieval-augmented generation (RAG) introduces an independent knowledge pipeline that selects relevant evidence at request time. This separates the lifecycle of enterprise knowledge from the lifecycle of model weights. Updating a policy document need not require retraining the model.
The architecture has two distinct planes: asynchronous ingestion and synchronous retrieval. Ingestion extracts, chunks, embeds and indexes content. Retrieval authenticates a caller, searches authorised content, assembles evidence and invokes the model. A production deployment must preserve document identifiers, versions and access policies across both planes.
02 — Document ingestion and object storage
MinIO or another S3-compatible object store can retain source documents and derived artefacts. A worker extracts text, normalises metadata and creates chunks with stable identifiers. Chunk boundaries should respect headings and semantic structure rather than blindly cutting every fixed number of characters. Overlap can preserve context but increases index size and duplicate retrieval.
Use a content hash and document version to make ingestion idempotent. A queue can decouple upload from parsing and embedding. Failed jobs should be retried with bounded backoff and eventually quarantined. Deletions must propagate to the vector index, caches and derived artefacts according to retention policy. Treat uploaded documents as untrusted input, including instructions embedded inside them.
03 — Embeddings and vector database architecture
An embedding model maps text into a numerical vector. Semantic retrieval compares query and document vectors in the same embedding space. Cosine similarity measures directional alignment; dot product and Euclidean distance have different properties. Select a metric appropriate to the embedding model and keep model version, dimensionality and preprocessing consistent.
Qdrant stores vectors with payload metadata and supports approximate nearest-neighbour search, including HNSW indexing. HNSW trades memory and search effort for recall. Payload filters can restrict results by tenant, document type or access group. Index rebuilds or parallel collections may be necessary when migrating embedding models; vectors from unrelated embedding spaces should not be mixed.
04 — Retrieval, reranking and context assembly
A query embedding retrieves candidate chunks, optionally combined with lexical search for exact identifiers and product names. A reranker can score query–document pairs more precisely at additional compute cost. Deduplicate overlapping chunks and assemble a bounded context with source references. Retrieval scores are not probabilities of factual correctness.
The prompt budget must include system instructions, conversation history, evidence and output allowance. A large context window is not a guarantee of effective retrieval. Evaluate recall at k, ranking quality, citation correctness and answer groundedness using representative questions. When evidence is insufficient, the application should abstain or ask for clarification rather than invent a source.
05 — Agent orchestration and durable execution
An agent extends inference with a controlled execution loop: observe state, choose an allowed action, execute a tool and incorporate the result. LangGraph can express this as a state graph with conditional edges and checkpoints. A deterministic workflow is often preferable for known business processes; reserve model-driven decisions for genuinely uncertain steps.
Persist checkpoints at meaningful boundaries and use idempotency keys for external writes. A resumed graph must not repeat a payment, ticket creation or infrastructure change simply because a worker crashed. Bound iterations, elapsed time and tool budgets. Human approval should precede sensitive actions, with the exact proposed operation visible to the approver.
06 — MCP and tool execution boundaries
The Model Context Protocol provides a standard interface between clients and servers exposing tools, resources and prompts. An agent application may discover tool schemas and invoke approved operations through an MCP client. MCP is not itself a universal authorisation layer: the host, server and downstream service must enforce identity, permissions and input validation.
Separate read-only diagnostic tools from write-capable tools. Use narrowly scoped credentials, network egress controls and audit logs. Treat tool results and retrieved text as data rather than privileged instructions. Validate arguments against schemas and enforce policy outside the model. Never allow a document to grant itself access to a tool or change the caller’s permissions.
07 — Persistent memory and enterprise isolation
Conversation state, long-term preferences, semantic knowledge and workflow checkpoints are different forms of memory. A relational database can retain structured state and checkpoint metadata; a vector database can retrieve relevant semantic memories. Object storage holds larger artefacts. Not every conversation should become durable memory.
Apply tenant isolation, consent and retention rules before writing or retrieving memory. Cache keys must include the appropriate security scope. Authorisation must be enforced at retrieval and tool execution, not just in a user interface. Keep provenance and timestamps so stale memories can be corrected or removed. Encrypt transport and storage and restrict service accounts to their required collections and buckets.
08 — Operating the cognitive infrastructure
Instrument ingestion lag, embedding throughput, index search latency, reranking latency, prompt length, model time to first token and tool execution duration. Trace a request across services using a correlation identifier while avoiding raw sensitive prompts in logs. Separate retrieval failures from inference failures: a fast model cannot compensate for missing or unauthorised evidence.
Start with a single host running an inference service, embedding worker, vector database and application. Add object storage and durable queues when the workload requires them. Scale embedding and retrieval independently of generation; reserve GPU resources according to measured contention. Back up metadata and source objects, test restoration, and verify that access revocation propagates through the entire system.
Vector capacity and context budget
Assumes 1,024 tokens for instructions and history and 1,024 reserved output tokens. Raw vector payload excludes HNSW, metadata, replicas and storage overhead. Representation options are conceptual; verify support in your chosen database.
Practical infrastructure inspection
Run against your own authorised deployment. The following examples assume local services and configured credentials where required.
docker ps docker stats --no-stream ss -lnt # Local Qdrant health (if exposed and authorised) curl --fail http://127.0.0.1:6333/healthz # Local Ollama model inventory curl --fail http://127.0.0.1:11434/api/tags # GPU allocation and utilisation nvidia-smi
Inspect service logs and request traces before changing index or model configuration. Do not expose unauthenticated service ports to the public internet.
Engineering checkpoint
A user receives evidence from another tenant even though model latency is normal. What should you investigate first?
Select an investigation.
Engineering note: this is an original conceptual architecture and educational estimator, not a live RAG deployment or benchmark. Technology choices are illustrative. Consult official project documentation for version-specific configuration.
Qdrant documentation · MCP documentation · LangGraph documentation
Enterprise RAG & Agent Execution Simulator
Follow the knowledge path from source documents to grounded answers and authorised tool calls. Inspect each stage, change retrieval parameters and inject failures into a private cognitive infrastructure.
01 / Engineering control plane
Ready to execute.
02 / Live architecture journey
Component inspector
Select a component to inspect its responsibility.
03 / Retrieval and context laboratory
Cosine similarity is calculated over small synthetic three-dimensional vectors. These are teaching vectors, not real embeddings. Tenant filtering precedes ranking; the optional reranking demonstration adds a small deterministic keyword bonus.
| Document | Cosine | Rank score | Tokens |
|---|
04 / Execution evidence
No events yet.
Response / tool result
Run the journey to inspect the simulated output.
No actual model, database, network request or tool invocation occurs. No credentials or personal data are collected.05 / Guided investigations
Investigation A — Retrieval quality versus context capacity
Run the healthy RAG journey with top K = 1, then top K = 5. Compare the selected evidence and token demand. A larger K does not guarantee better grounding. Reduce the context window and observe admission failure if the budget is exceeded.
Investigation B — Tenant isolation
Select the unauthorised document scenario. Observe that the access check blocks the request before vector retrieval. In production, enforce document-level access on the server and never trust a model to enforce authorisation.
Investigation C — MCP permission boundary
Select Agent and MCP tool execution, then Tool permission denied. Step through retrieval and planning. The tool gateway must deny the call before execution; the agent should return a controlled failure, not bypass the policy.
Engineering checkpoint
Where should access to a privileged tool be enforced?
06 / Production field notes
Use Qdrant payload filters to constrain retrieval by authorised tenant and document scope. Store original documents in object storage such as MinIO and keep source identifiers and versions with every chunk. Treat retrieved content as untrusted data. LangGraph can coordinate stateful workflows; MCP standardises tool interaction but does not replace authentication or authorisation. Persist only approved memory, with retention and deletion policies.
curl --fail http://localhost:6333/collections curl --fail http://localhost:9000/minio/health/live ss -lntp nvidia-smiIllustrative local diagnostic commands; ports and authentication depend on your deployment. Do not expose unauthenticated services publicly.
AI Infrastructure Security and Observability
A private AI platform is not secure simply because it runs on private hardware. Production readiness depends on explicit trust boundaries, enforceable permissions and evidence that the infrastructure behaves as intended.
Follow a request across the trust boundary
Zero Trust begins with identity, not location
An internal subnet is not an identity. Every inference client should authenticate at a gateway, and every service should receive only the permissions needed for its role. Short-lived credentials, workload identities and mutual TLS reduce dependence on static shared secrets. Authentication establishes who is calling; authorization determines which model, tenant, dataset or tool that caller may access.
A gateway must validate token signature, issuer, audience and expiry, then enforce resource-level authorization. Rate limits and request size limits protect capacity but do not replace authorization. Internal services should verify the identity or trusted delegation presented to them rather than blindly trusting forwarded headers.
Segmentation and workload isolation
Separate management, inference, storage and distributed GPU traffic according to operational needs. Kubernetes NetworkPolicy can restrict pod connectivity when the installed network plugin enforces it. A default-deny policy requires explicit DNS and service allowances; apply changes in a test environment before production. Network controls do not replace application-level tenant checks.
Containers share a host kernel. Namespaces and cgroups provide resource and visibility boundaries, but a hostile multi-tenant workload may warrant stronger isolation through dedicated nodes or virtual machines. GPU device access must be explicitly assigned. MIG on supported GPUs partitions compute and memory resources; it does not by itself establish an end-to-end security boundary for the application, host or network.
Protect the model and its supply chain
Treat model weights, container images, drivers and dependencies as controlled software artifacts. Record provenance, verify trusted hashes or signatures where available, scan images and restrict write access to registries. Prefer safe serialization formats where supported and avoid loading untrusted executable model code. A model license is a separate concern from its technical integrity.
Keep secrets outside images and prompts. Use a secret manager or protected runtime injection, rotate credentials, and restrict outbound network access. A compromised inference process should not automatically gain access to object storage administration or cluster credentials. Maintain a tested rollback path for driver, runtime and model upgrades.
RAG, MCP and agent trust boundaries
Retrieved documents and tool responses are untrusted data. A document can contain instructions designed to manipulate an agent. Separate system policy from retrieved content, validate structured tool arguments, and enforce permissions in the tool service itself. Prompt instructions are not an authorization mechanism.
For MCP deployments, authenticate clients and authorize individual tools and resources. Use narrowly scoped credentials and validate token audiences where applicable. Require explicit approval for sensitive or irreversible actions, restrict egress, and avoid passing upstream access tokens to unrelated downstream services. Enforce tenant filtering during retrieval, not merely after a model has seen the documents.
Observability: metrics, logs and traces
Prometheus collects numerical time series; Grafana visualizes and correlates operational signals. OpenTelemetry provides instrumentation and collection for traces, metrics and logs, with exporters sending signals to configured backends. These components complement each other rather than replacing one another.
Propagate a request identifier and trace context from gateway to scheduler, retrieval service and tool execution. Record latency, queue depth, token counts, errors and GPU memory pressure. Avoid recording raw prompts, credentials or sensitive retrieved content by default. Keep high-cardinality request IDs in traces or logs rather than metric labels.
Diagnose inference performance with evidence
Time to first token includes admission, queueing, prompt processing and other overhead. Inter-token latency reflects the cadence of generated tokens. End-to-end latency includes the full response. Track percentiles and distinguish successful requests from rejected or failed requests. Averages can hide a small population of severely delayed requests.
GPU utilization alone cannot identify a bottleneck. Compare memory bandwidth, allocated memory, scheduler queue depth, request arrival rates and token throughput. NVIDIA DCGM metrics can help correlate device health with inference telemetry. A rising queue with stable service throughput indicates demand may exceed available capacity; verify the workload mix before adding hardware.
Operational resilience and incident response
Set service objectives for availability and latency, then define alert thresholds based on sustained user impact. Establish runbooks for GPU failures, exhausted KV cache, failed authentication and unavailable retrieval services. Health checks should distinguish process liveness from readiness to accept inference traffic.
Test backups of configuration, vector indexes and source documents, and verify restoration. Define retention and access controls for telemetry. During an incident, preserve relevant evidence, contain the fault and verify recovery with a known test request. Security and observability are continuous engineering disciplines, not final installation steps.
Estimate trace ingestion volume
Sampling controls telemetry volume, but aggressive sampling may hide rare failures. This model assumes a fixed number of spans and bytes per span; it excludes logs, metrics, compression and backend overhead.
Formula: requests/s × spans/request × sampling fraction × bytes/span × 86,400 ÷ 1,000,000,000.
Production diagnostic field notes
Run these read-only inspections only on infrastructure you administer. Kubernetes and NVIDIA commands require the relevant tools and permissions.
ss -lntp ip route show nvidia-smi kubectl get networkpolicy -A kubectl get pods -A kubectl top pods -A
Inspect listening services, routes, GPU health, policy objects and workload resource use. A listed NetworkPolicy does not prove enforcement; validate with authorized connectivity tests. kubectl top requires a working metrics API.
Engineering checkpoint
An agent retrieves a document containing an instruction to export another tenant’s records. What is the strongest control?
Select an answer to investigate.
Original educational engineering analysis. Architecture and calculations are illustrative, not a security certification or measured production benchmark. See the Legal & Editorial Centre.
AI Infrastructure Security & Observability Command Centre
Follow a request across explicit trust boundaries. Inspect identity, policy, retrieval and tool execution decisions, then correlate security events with operational telemetry. A private network is not itself proof of trust.
01 / Incident control plane
Ready
02 / Trust boundaries and execution path
Select any component to inspect its role. Numbered nodes show logical execution order, not physical network hops.
03 / Engineering telemetry
Illustrative GPU memory utilisation: 0%
Trace sampling is modelled deterministically for this demonstration; security audit events are kept separately from sampled traces. A collector outage does not imply a workload outage.
Local incident event console
Awaiting execution.
04 / Guided engineering investigations
Choose an investigation, then step through the request to locate the first failing boundary.
Engineering interpretation and remediation
Authentication establishes an identity; authorization decides what that identity may do. Enforce tenant filtering on the server side before documents enter model context. Treat retrieved content and model-generated tool arguments as untrusted. Validate tool schemas and permissions independently, and require human approval for sensitive actions where appropriate.
Network policies restrict connectivity but do not replace application authorization. GPU memory exhaustion is a capacity incident, not necessarily a security breach. Compare request errors, queue depth, GPU memory and traces before deciding whether to scale or change admission limits.
Prompt injection detection is imperfect. Layer least privilege, constrained tool interfaces, data access enforcement and approval boundaries rather than relying on a classifier alone.
05 / Operational diagnostic reference
kubectl get networkpolicy -A kubectl auth can-i get pods --namespace ai kubectl get events -n ai --sort-by=.lastTimestamp kubectl logs -n ai deployment/otel-collector --tail=100 nvidia-smi --query-gpu=memory.used,memory.total,utilization.gpu --format=csv ss -lntp
Read-only examples for an authorized environment. Namespace and deployment names are illustrative. Kubernetes RBAC inspection does not establish application-level RAG or MCP permissions.
Knowledge checkpoint
A valid agent identity requests a tool outside its assigned scope. What should the gateway do?
Educational simulation only. No real credentials, network requests, AI models, security enforcement or telemetry backends are used. Timings and memory values are illustrative.
Building and Operating a Production Private AI Platform
From a single Linux server to a resilient enterprise AI service: integrate compute, networking, model serving, knowledge, security and operations into a measurable engineering system.
Choose a deployment scale
Conceptual logical stack: security and observability apply across all layers; the arrows do not imply that every request traverses every service.
01 · Establish the workload contract
Start with the model, its licence, maximum context length, expected concurrent requests and acceptable time to first token. Separate interactive chat from batch embedding and agent workloads: their resource profiles and service objectives differ. Establish a representative evaluation dataset before selecting hardware. A model that fits in memory is not necessarily fast enough to meet a service objective.
Measure prompt and output token distributions, request arrival rates and p95 latency under representative load. Record the model revision, tokenizer, quantisation and serving configuration so results are reproducible.
02 · Build the physical and Linux foundation
Select CPU, RAM, GPU memory, PCIe topology, NVMe capacity, power and cooling as a system. On multi-socket servers, inspect NUMA placement and GPU affinity. Install a supported Linux distribution and a compatible NVIDIA driver; validate the device before introducing containers. Keep management access separate from workload traffic.
Reserve capacity for model weights, KV cache, runtime buffers and host-side processing. Check sustained thermals and storage throughput rather than relying on peak specifications. Pin tested software versions and maintain a rollback path.
03 · Introduce the serving runtime
For a small private lab, Ollama can simplify model lifecycle and local inference. For higher concurrency, evaluate vLLM and its batching and KV cache management. NVIDIA Triton is another serving option, with capabilities dependent on the selected backend. These are alternatives or complementary components, not mandatory layers.
Bind internal services to private interfaces and expose a controlled gateway rather than a raw model endpoint. Apply authentication, request limits, timeouts and model-specific context limits. Benchmark prefill and decode separately; aggregate tokens per second can conceal poor interactive latency.
04 · Add orchestration only when justified
A single host can run a containerised service without Kubernetes. As the deployment grows, Kubernetes can manage replicas, resource requests, health checks and rollouts. The NVIDIA device plugin advertises GPU resources; the GPU Operator can manage supported driver and runtime components. GPU scheduling must account for memory and topology, not simply device count.
Use readiness checks that reflect model availability, not merely a listening port. Plan for long model loading times and graceful draining. A second replica on the same host does not protect against host failure. Separate failure domains and test recovery.
05 · Engineer the network and storage
Use a segmented Ethernet network for management, client traffic and storage. Multi-node tensor or pipeline parallelism may require a high-bandwidth, low-latency fabric; evaluate Ethernet RDMA or InfiniBand where workload measurements justify it. BGP and ECMP can provide scalable underlay connectivity, but do not by themselves guarantee balanced collective traffic.
Store model artefacts in a controlled repository with checksums and access policy. Object storage such as MinIO can support document and artefact workflows. Local NVMe can reduce cold-start loading delays; maintain durable copies and test restore procedures.
06 · Add knowledge and agent services
A RAG pipeline ingests documents, chunks content, generates embeddings and indexes vectors in a service such as Qdrant. Retrieval must enforce tenant and document permissions before content enters the prompt. Track source provenance and evaluate retrieval quality independently of generation.
Agent orchestration such as LangGraph can manage explicit state and execution transitions. MCP can expose tools through a controlled interface. Treat retrieved text and tool output as untrusted data; enforce permissions outside the model, use bounded execution and require approval for sensitive actions.
07 · Secure and observe every layer
Use workload identity, least privilege, encrypted transport, secret management and network segmentation. Verify model and container provenance. Avoid logging sensitive prompts or credentials by default. Apply retention and deletion policies to traces, documents and agent memory.
Prometheus can collect metrics, Grafana can visualise them and OpenTelemetry can instrument request traces. NVIDIA DCGM can expose supported GPU metrics. Correlate queue delay, time to first token, decode rate, GPU memory and errors with request identifiers. Alert on service objectives rather than GPU utilisation alone.
08 · Operate through change and failure
Maintain versioned configuration, tested backups, recovery objectives and a deployment runbook. Canary new models and runtimes against representative traffic before expanding rollout. Record quality, latency and resource consumption alongside security and compatibility checks.
Practise GPU failure, node loss, exhausted KV cache, unavailable retrieval and gateway overload. Decide whether to reject, queue, degrade or fail over requests. Retries must be bounded and safe for tool actions. Recovery is complete only when service health and data integrity are verified.
09 · Production acceptance
A production platform is a set of verified operational capabilities, not a collection of installed products. Define measurable acceptance criteria for quality, latency, throughput, isolation, recovery and cost. Document ownership and escalation routes.
Start small, measure, and add complexity only when evidence supports it. The next interactive capstone will let readers practise these decisions in a conceptual deployment and troubleshooting environment.
Estimate serving replica requirements
Decode-only steady-state estimate: ceil(request rate × output tokens ÷ (replica throughput × utilisation)). Prefill, burstiness, memory, latency objectives and failure domains require separate validation. Defaults are illustrative, not benchmarks.
Read-only operational inspection
lscpu free -h lsblk lspci -nn nvidia-smi nvidia-smi topo -m ip -br addr ss -lnt # If Kubernetes is deployed: kubectl get nodes kubectl get pods -A kubectl get events -A --sort-by=.metadata.creationTimestamp
Run commands only on systems you administer. Kubernetes and NVIDIA commands require the relevant tools and permissions.
Production readiness checklist
Use this local checklist to review deployment gates. Checking a box records your review only; it does not validate infrastructure.
Engineering checkpoint
Two replicas share one physical GPU server. What is the most important limitation?
Private AI Infrastructure — Deployment & Troubleshooting Capstone
Build a reference platform, validate its dependencies and follow a synthetic enterprise AI request from identity enforcement to retrieval, inference and telemetry. Diagnose failures using evidence before applying a repair.
Educational simulation only. No commands are executed, no network requests are made and no real infrastructure is provisioned. Capacity figures are estimates, not benchmarks.
01 / Infrastructure design
Capacity model and assumptions
Weights = parameters × bits / 8. KV cache assumes a hypothetical grouped-query transformer with 32 layers, 8 KV heads, head dimension 128 and BF16 cache, regardless of selected parameter count. Cache = 2 × layers × heads × dimension × 2 bytes × tokens × concurrency. We assume ideal even sharding of weights and cache and reserve 2 GiB per GPU. Real models differ; tensor parallelism compatibility, allocator overhead, activations and quantisation metadata must be validated independently. Network rate is nominal, not effective throughput.
02 / Deployment and incident control
Configure infrastructure and deploy.
Select an architecture component to inspect its responsibility.
03 / Engineering telemetry
Incident event console
Awaiting deployment.
04 / Guided engineering investigations
Investigation A — GPU capacity failure
Select one 16 GiB GPU, 70B BF16 weights and deploy. Observe the capacity rejection. Reduce model size or increase compatible GPU capacity, then deploy again. Explain why aggregate memory alone cannot guarantee model placement.
Investigation B — Retrieval outage
Choose the team preset and RAG workload. Inject a vector service outage, deploy, run a request and step through the architecture. Identify the failed dependency, select its remediation and rerun. Distinguish retrieval failure from GPU inference failure.
Investigation C — Tool authorization
Choose the agent workload and inject tool permission denial. Run a request. Verify that inference can succeed while the tool call is blocked. Review the narrow permission required; do not grant unrestricted access.
Investigation D — Observability degradation
Inject a telemetry collector outage and run a healthy inference request. Notice that the response succeeds while trace delivery fails. Restore the collector and rerun to validate visibility.
05 / Production diagnostic field guide
These are read-only inspection examples for an authorized environment. Replace namespaces and service names with your own deployment values.
nvidia-smi nvidia-smi topo -m lspci -nn free -h ip route ip -s link ss -lnt lsblk kubectl get pods -A kubectl get events -A --sort-by=.lastTimestamp kubectl -n ai logs deployment/model-server --tail=100 kubectl -n ai get networkpolicy kubectl -n ai get serviceaccounts
Correlate timestamps, request IDs, GPU memory, network counters and application logs. Avoid restarting every component indiscriminately; isolate the failing dependency, apply the smallest justified change and verify recovery.
Knowledge checkpoint
A request generates tokens successfully but no trace appears in the observability backend. Which dependency should you investigate first?
06 / Capstone completion
Complete a healthy request and resolve at least one incident to finish the capstone.
Next steps: validate this reference architecture against actual hardware, model documentation, measured throughput, security requirements and recovery objectives before production deployment.
- Linux Virtualisation and Virtual Networking for AI Infrastructure - December 4, 2026
- Building a Linux AI Server - December 4, 2026
- From Bare Metal to Production AI Inference - December 4, 2026
