PCI passthrough on a multi-GPU server is a very different engineering problem from a single consumer card in a desktop. IOMMU groups you cannot control, a management plane that disappears when there is no onboard graphics, the effect of PCIe topology on P2P traffic, thermal stability under long loads — the flood of “passthrough tutorials” online hardly mentions any of this, and these are exactly the places where production setups fail.
This post is mainly about a headless 4x RTX 3090 machine: the configuration flow for GPU passthrough under PVE, the pitfalls, and measured data (CUDA bandwidth, PyTorch training, vLLM inference). There is also an 8x V100 data-center platform, and its configuration differences are covered too. I have not collected performance numbers on the V100 yet, so I make none up; those sections keep only the method.
Hardware Platform and Architecture Decisions
Platform Specs
| Item | Platform A: 4x RTX 3090 | Platform B: 8x V100 |
|---|---|---|
| Host IP | 192.168.1.2 | 192.168.1.3 |
| GPU | NVIDIA RTX 3090 x4 | NVIDIA V100 (SXM2/PCIe) x8 |
| CPU | AMD Ryzen Threadripper 3960X (24C/48T) | Dual Intel Xeon Gold 6138 @ 2.00GHz (40C/80T) |
| Memory | 128 GB (32GB x4) DDR4 | 256 GB ECC DDR4 |
| Motherboard/chassis | ASRock TRX40 Creator | Inspur NF5468M5 |
| Onboard graphics | None | Dedicated AST2500 BMC |
| Management | IP / SSH only | IPMI out-of-band management |
Network Topology and IP Plan
So the GPU inference layer, LLM gateway, OpenClaw agent and monitoring stack can work together safely and efficiently, we first plan the addressing for the physical hosts and the VMs. Every node talks at layer 2 through PVE’s virtual bridge (such as vmbr0):
| Node role | IP address | Host | Core components |
|---|---|---|---|
| PVE host 1 | 192.168.1.2 |
Physical machine A | PVE system, PCIe passthrough management |
| PVE host 2 | 192.168.1.3 |
Physical machine B | PVE system, NVLink / PCIe passthrough management |
| 3090 inference VM | 192.168.1.20 |
PVE 1 (Platform A) | vLLM instance (4x 3090 attached) |
| V100 inference VM | 192.168.1.21 |
PVE 2 (Platform B) | vLLM instance (8x V100 attached) |
| LLM routing gateway | 192.168.1.12 |
PVE 1 or 2 | LiteLLM (unified API gateway), auth and rate limiting |
| OpenClaw VM | 192.168.1.11 |
PVE 1 or 2 | OpenClaw Gateway, agent, Docker sandbox |
| Automation workflows | 192.168.1.13 |
PVE 1 or 2 | n8n (triggered through the agent) |
| LLM tracing | 192.168.1.14 |
PVE 1 or 2 | Langfuse (LLM trace auditing and observability) |
| Global monitoring node | 192.168.1.30 |
PVE 1 or 2 | Prometheus, Grafana |
The multi-model AI agent architecture and network topology for the whole Homelab looks like this:
graph TB
subgraph Management["Management plane (192.168.1.x)"]
PROM["Global monitoring node<br/>192.168.1.30<br/>Prometheus/Grafana"]
LF["LLM tracing node<br/>192.168.1.14<br/>Langfuse"]
PVE1["PVE host 1<br/>192.168.1.2<br/>(4x RTX 3090)"]
PVE2["PVE host 2<br/>192.168.1.3<br/>(8x V100)"]
end
subgraph Application["Application plane (192.168.1.x)"]
OC["OpenClaw Agent<br/>192.168.1.11"]
N8N["n8n workflows<br/>192.168.1.13"]
end
subgraph Gateway["Gateway plane"]
LITE["LLM routing gateway<br/>192.168.1.12<br/>LiteLLM Proxy"]
end
subgraph Compute["GPU inference layer"]
VM3090["3090 inference VM<br/>192.168.1.20<br/>vLLM"]
VMV100["V100 inference VM<br/>192.168.1.21<br/>vLLM"]
end
%% business traffic
OC -->|"HTTPS+Key"| LITE
N8N -->|"HTTPS+Key"| LITE
LITE -->|"localhost (loopback) / direct"| VM3090
LITE -->|"direct"| VMV100
%% audit and monitoring traffic
LITE -.->|"async tracing"| LF
PROM -.->|"scrape metrics"| VM3090
PROM -.->|"scrape metrics"| VMV100
PROM -.->|"scrape metrics"| PVE1
PROM -.->|"scrape metrics"| PVE2
classDef vm fill:#e3f2fd,stroke:#1565c0,stroke-width:2px;
classDef host fill:#f5f5f5,stroke:#424242,stroke-width:2px;
classDef gw fill:#fff3e0,stroke:#e65100,stroke-width:2px;
class OC,N8N,VM3090,VMV100,LF vm;
class LITE,PROM gw;
class PVE1,PVE2 host;
Architecture notes:
- The LLM routing gateway (
1.12) is where all traffic converges. Neither OpenClaw (1.11) nor n8n (1.13) is allowed to connect directly to the inference VMs underneath (1.20and1.21).- Only the LLM routing gateway has access to the inference VMs underneath (ports
8001-8003and so on), which keeps the security boundary at one layer: the gateway.
Platform Differences and Passthrough Strategy
The two platforms differ not just in GPU model but across the whole I/O architecture:
Platform A (4x 3090, ASRock TRX40) has one core challenge: no onboard graphics. This is not a small problem — it directly determines whether the management plane is usable. If all four GPUs are bound to VFIO, the host has no framebuffer device at all, not even a GRUB boot screen.
What I did on Platform A: manage it over SSH and the PVE Web UI only. The PVE management plane itself does not depend on a GPU, and as long as the network works the Web UI is there. If a configuration mistake cuts the network, the only way back is to pull the disk and fix the network config offline, or to put a cheap display card in the motherboard temporarily.
Platform B (8x V100, Inspur NF5468M5) is a standard rack-mount AI server with a dedicated BMC/IPMI port, so managing it without a GUI is not a problem. The complexity here is NUMA node binding and PCIe topology. The dual-socket Intel Xeon Gold design means the eight cards are actually attached to different CPU sockets. If a VM is scheduled across NUMA nodes, or it is passed a NIC and a GPU that do not belong to the same CPU, the QPI/UPI interconnect latency penalty is severe.
BIOS Configuration
BIOS settings are the foundation of GPU passthrough. Miss one item and you get a black screen at boot or a BAR allocation failure. These are the items to confirm:
| BIOS option | Requirement | Notes |
|---|---|---|
| VT-d / AMD-Vi | Enabled | Base of IOMMU; nothing works without it |
| SR-IOV | Enabled if available | Reserved for a later vGPU setup |
| Above 4G Decoding | Must be enabled | Required for multiple cards. A single 3090 already has a 256MB BAR1; four cards need far more than the 4GB addressing limit |
| Resizable BAR (ReBAR) | Disable as appropriate | On some firmware/QEMU versions ReBAR makes GPU init fail inside the VM (Code 43) |
| CSM | Disabled | OVMF needs a pure UEFI environment; CSM compatibility mode introduces unpredictable problems |
From experience: Above 4G Decoding is the most commonly overlooked option in multi-GPU passthrough. The symptom is
nvidia-smiinside the VM printingUnable to determine the device handle for GPU, with aBAR 1: can't assignerror in dmesg.
PVE Host Configuration
IOMMU and Kernel Parameters
Edit /etc/default/grub and add to GRUB_CMDLINE_LINUX_DEFAULT:
Intel platform:
GRUB_CMDLINE_LINUX_DEFAULT="quiet intel_iommu=on iommu=pt pcie_acs_override=downstream,multifunction video=efifb:off"
AMD platform:
# AMD platforms use amd_iommu=on; on Intel, switch it to intel_iommu=on
GRUB_CMDLINE_LINUX_DEFAULT="quiet amd_iommu=on iommu=pt pcie_acs_override=downstream,multifunction video=efifb:off"
Line by line:
| Parameter | Effect | Why it is needed |
|---|---|---|
intel_iommu=on / amd_iommu=on |
Enables IOMMU | Prerequisite for passthrough |
iommu=pt |
Pass-through mode | Non-passthrough devices take the direct DMA path, avoiding unnecessary IOMMU translation overhead |
pcie_acs_override=downstream,multifunction |
Forces IOMMU group splitting | Almost certainly needed on multi-GPU servers — several GPUs behind a PCIe switch often land in the same IOMMU group |
video=efifb:off |
Disables the EFI framebuffer | Stops the host kernel from binding the GPU’s framebuffer device so VFIO can take it over cleanly |
update-grub && reboot
After the reboot, confirm:
dmesg | grep -e DMAR -e IOMMU
# You should see "DMAR: IOMMU enabled" or "AMD-Vi: Initialized"
VFIO Module Loading
Edit /etc/modules:
vfio
vfio_iommu_type1
vfio_pci
Since Linux 6.2,
vfio_virqfdhas been merged into VFIO and no longer needs to be loaded separately. If an older guide still has that line, delete it.
IOMMU Groups: The Key to Whether Passthrough Works
IOMMU groups decide both whether passthrough is possible and how fine-grained it is. Every device in a group is either passed through or all left to the host.
#!/bin/bash
shopt -s nullglob
for g in $(find /sys/kernel/iommu_groups/* -maxdepth 0 -type d | sort -V); do
echo "IOMMU Group ${g##*/}:"
for d in $g/devices/*; do
echo -e "\t$(lspci -nns ${d##*/})"
done;
done;
Platform A (4x RTX 3090)
Actual group output varies with the board and BIOS, so I won’t paste a fixed result. After running the script above, look at two things:
- Whether each 3090 is in the same group as its HDMI audio controller. When passing it through, give the VM both the display and audio functions.
- Whether several cards have been merged into one group. This is common in multi-switch PCIe topologies, and if so the only option is to split groups with
pcie_acs_override. Splitting bypasses the isolation that ACS (Access Control Services) provides, so weigh the risk in security-sensitive setups.
Platform B (8x V100)
The PCIe topology of V100 SXM2 is far more complex than a consumer platform; NVLink bridge devices and PLX switches can both show up in IOMMU groups. The things to confirm: whether a group allows a single GPU to be passed through on its own, and whether the NVLink interconnect devices are grouped with it.
VFIO-PCI Binding
lspci -nn | grep -i nvidia
Example output (replace the bus addresses with those on your machine):
41:00.0 VGA compatible controller [0300]: NVIDIA Corporation GA102 [GeForce RTX 3090] [10de:2204] (rev a1)
41:00.1 Audio device [0403]: NVIDIA Corporation GA102 High Definition Audio Controller [10de:1aef] (rev a1)
Bind to VFIO:
echo "options vfio-pci ids=10de:2204,10de:1aef disable_vga=1" > /etc/modprobe.d/vfio.conf
disable_vga=1is essential. Without this option, VFIO tries to do VGA arbitration when binding a VGA-class device, which on a platform with no onboard graphics leads straight to a failed bind or a kernel hang.
Blocking the Host NVIDIA Driver
cat >> /etc/modprobe.d/blacklist.conf << 'EOF'
blacklist nouveau
blacklist nvidia
blacklist nvidiafb
blacklist nvidia_drm
EOF
update-initramfs -u -k all && reboot
After the reboot, confirm the binding:
lspci -nnk -s 41:00
# Kernel driver in use: vfio-pci
If you see Kernel driver in use: nouveau or nvidia, the blacklist did not take effect — check that the initramfs was rebuilt, or that no other modprobe config file is loading the NVIDIA modules.
VM Configuration
Key Parameters
| Setting | Recommended | Reason |
|---|---|---|
| Machine type | q35 |
i440fx emulates PCIe only partially; q35 provides full PCIe topology support |
| BIOS | OVMF (UEFI) |
NVIDIA GPU VBIOS needs a UEFI environment to initialize |
| CPU type | host |
Exposes the real CPU features (such as AVX-512) so the GPU driver does not error out on missing CPU features after passthrough |
| Memory | Fixed allocation, ballooning disabled | Memory ballooning conflicts with the DMA mappings of VFIO devices; enabling it will most likely crash the VM |
PCI Device Passthrough
Edit /etc/pve/qemu-server/<VMID>.conf directly:
# single GPU passthrough
hostpci0: 0000:41:00,pcie=1,x-vga=1
# all four RTX 3090s passed through to the same VM
hostpci0: 0000:41:00,pcie=1,x-vga=1
hostpci1: 0000:61:00,pcie=1
hostpci2: 0000:81:00,pcie=1
hostpci3: 0000:a1:00,pcie=1
x-vga=1is set only on the primary GPU. It tells QEMU to hand that device’s VGA arbitration to the VM. With multiple cards, onlyhostpci0needs the flag.
When adding a PCI device in the Web UI, note: tick All Functions (passes through both the GPU and its audio controller), ROM-Bar, and PCI-Express. Tick Primary GPU only for the main card that needs VGA output.
Building a Clean Debian 13 (Trixie) Base Image
To keep the inference node absolutely clean with no overhead from extra services, I skipped the usual ISO install inside the PVE VM and built a minimal Debian 13 environment by hand with debootstrap. Any Live CD (SystemRescue, for example) can boot the VM.
1. Disk Partitioning and Mounting
# Assuming the target disk is /dev/sda, partition it with fdisk:
# sda1: EFI (FAT32)
# sda2: Boot (Ext4)
# sda3: Root (Ext4)
apt install -y dosfstools cryptsetup efibootmgr debootstrap
mkfs.fat -F32 /dev/sda1
mkfs.ext4 /dev/sda2
mkfs.ext4 /dev/sda3
# Create the mount structure
mkdir -pv /mnt/debinst
mount /dev/sda3 /mnt/debinst/
mkdir -pv /mnt/debinst/boot
mount /dev/sda2 /mnt/debinst/boot/
mkdir -pv /mnt/debinst/boot/efi
mount /dev/sda1 /mnt/debinst/boot/efi/
2. Pulling the Base System and Entering Chroot
Pull the Debian 13 (Trixie) amd64 base packages from a fast mirror:
debootstrap --arch amd64 trixie /mnt/debinst https://mirrors.tuna.tsinghua.edu.cn/debian/
# Bind the necessary core filesystems
mount -v -t proc none /mnt/debinst/proc
mount -v --rbind /sys /mnt/debinst/sys
mount -v --rbind /dev /mnt/debinst/dev
mount -v --make-rslave /mnt/debinst/sys
mount -v --make-rslave /mnt/debinst/dev
# Switch into the real VM environment
LANG=C.UTF-8 chroot /mnt/debinst /bin/bash
3. Initializing the Environment Inside Chroot
Install the basic tools and configure the mount table and network topology (using the V100 node 192.168.1.21 as the example):
apt update
apt install -y apt-transport-https ca-certificates aptitude vim dosfstools efibootmgr lvm2
# Fill in the UUIDs of the partitions just created (get them with blkid)
cat <<EOF > /etc/fstab
UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx / ext4 defaults,relatime 0 1
UUID=xxxx-xxxx /boot/efi vfat defaults 0 1
UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx /boot ext4 defaults,relatime 0 1
EOF
# Hostname and DNS
echo v100-cluster > /etc/hostname
echo nameserver 114.114.114.114 > /etc/resolv.conf
# Static network configuration
cat <<EOF > /etc/network/interfaces
auto ens18
iface ens18 inet static
address 192.168.1.21
network 192.168.1.0
netmask 255.255.255.0
broadcast 192.168.1.255
gateway 192.168.1.1
EOF
Switch to the Tsinghua Trixie apt sources and configure localization:
cat <<EOF > /etc/apt/sources.list
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ trixie main contrib non-free non-free-firmware
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ trixie-updates main contrib non-free non-free-firmware
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ trixie-backports main contrib non-free non-free-firmware
deb https://mirrors.tuna.tsinghua.edu.cn/debian-security trixie-security main contrib non-free non-free-firmware
EOF
aptitude update
aptitude install locales tzdata
dpkg-reconfigure locales
dpkg-reconfigure tzdata
4. Finishing with the Kernel, GRUB and SSH
apt-get install linux-image-amd64
# The EFI bootloader is required
aptitude install grub-efi
grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=Proxmox
grub-mkconfig -o /boot/grub/grub.cfg
# Allow root SSH login; important on a headless server
apt-get install ssh -y
sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
passwd
exit
umount -R /mnt/debinst
reboot
Compiling Drivers on the VM and Verifying the Baseline
Once the freshly built Trixie system is rebooted, the first task is to build and load the NVIDIA proprietary driver and get a PyTorch test running, to confirm passthrough works all the way down.
1. Installing the NVIDIA Driver with DKMS
Building the driver module through DKMS gives better compatibility and control when the kernel is updated:
apt update
apt-get install -y pciutils linux-headers-$(uname -r) build-essential dkms
# Install the proprietary driver
apt install -y nvidia-driver
dpkg-reconfigure nvidia-kernel-dkms
modprobe nvidia
# Verify passthrough
nvidia-smi
2. PyTorch GPU Verification Environment
apt install -y python3-venv python3-pip
python3 -m venv gpu_test_env
source gpu_test_env/bin/activate
# Use a faster mirror
python -m pip install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple --upgrade pip
pip config set global.index-url https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
# Install only the core compute libraries
pip install torch torchvision torchaudio
# Check that PyTorch sees the GPU
python -c "import torch; print(f'CUDA available: {torch.cuda.is_available()}'); print(f'GPU count: {torch.cuda.device_count()}')"
3. Multi-GPU Topology Verification: Do Not Skip This Step
The test is not just about seeing the cards, but how they are connected:
Platform A: 4x RTX 3090
nvidia-smi topo -m
GPU0 GPU1 GPU2 GPU3 CPU Affinity NUMA Affinity GPU NUMA ID
GPU0 X PHB PHB PHB 0-31 0 N/A
GPU1 PHB X PHB PHB 0-31 0 N/A
GPU2 PHB PHB X PHB 0-31 0 N/A
GPU3 PHB PHB PHB X 0-31 0 N/A
...
Reading it: because of how the board and the CPU PCIe controllers are wired, the RTX 3090s interconnect as
PHB(crossing the CPU’s PCIe host bridge), with no NVLink.
Platform B: 8x V100-SXM2
nvidia-smi topo -m
GPU0 GPU1 GPU2 GPU3 GPU4 GPU5 GPU6 GPU7 CPU Affinity NUMA Affinity GPU NUMA ID
GPU0 X NV2 NV2 NV1 PHB PHB PHB NV1 0-39 0 N/A
GPU1 NV2 X NV1 NV2 PHB PHB NV1 PHB 0-39 0 N/A
...
nvidia-smi nvlink -s
GPU 0: Tesla V100-SXM2-32GB (UUID: GPU-4a303885-0edf-7219-d89d-f863a9e11366)
Link 0: 25.781 GB/s
Link 1: 25.781 GB/s
...
Reading it: the
NV1andNV2markers on the V100 cluster, plus NVLink link state at25.781 GB/s, show that PVE handles the PCIe topology and NVSwitch passthrough of an SXM2 baseboard very well. The output ofnvidia-smi topo -mdetermines communication efficiency in multi-GPU training. Under passthrough, if this degrades to SYS or PIX, AllReduce performance in distributed training takes a devastating hit.
Performance Benchmarks
Test Methodology
Tool Matrix
| Tool | Purpose | Version |
|---|---|---|
nvbandwidth |
PCIe bandwidth, P2P communication | v0.8 (Release) |
gpu-burn |
Compute correctness + thermal stability | 1.1.0 (Commit: 8a24c…) |
PyTorch |
DDP training throughput | 2.4.1+cu121 |
vLLM |
High-throughput LLM inference | Latest stable (version chosen to match model support) |
Prometheus + Grafana + dcgm-exporter |
End-to-end GPU observability | v2.54 / v11.2 / 3.3.8 (debian12) |
PCIe Bandwidth Test
P2P communication and raw hardware bandwidth are the core of measuring passthrough overhead, so here I use NVIDIA’s current official measurement tool: nvbandwidth (it has fully replaced the older cuda-samples bandwidth library).
apt install -y git cmake libboost-program-options-dev nvidia-cuda-toolkit build-essential
# Build the latest NVIDIA nvbandwidth tool
git clone https://github.com/NVIDIA/nvbandwidth.git
cd nvbandwidth
cmake . && make
# Host-to-device / device-to-host bandwidth
./nvbandwidth -t host_to_device_memcpy_ce
./nvbandwidth -t device_to_host_memcpy_ce
# GPU-to-GPU P2P bandwidth (device-to-device)
./nvbandwidth -t device_to_device_memcpy_ce
nvbandwidth already uses the optimal transfer sizes by default, so the results reflect the capability of the PCIe lanes themselves after passthrough.
H2D / D2H bandwidth:
Note: on Platform A, the board’s lane allocation gives the four RTX 3090s uneven PCIe lanes (GPU 0/1 run at PCIe 4.0 x16, GPU 2/3 at x8).
| Test | RTX 3090 (passthrough) |
|---|---|
| H2D (GB/s) | ~25.4 (x16) / 13.4 (x8) |
| D2H (GB/s) | ~25.2 (x16) / 13.2 (x8) |
P2P multi-GPU communication:
P2P is measured with ./nvbandwidth -t device_to_device_memcpy_ce. I did not keep the 4x 3090 P2P numbers, so there are no concrete values here; the way to judge is whether bandwidth falls off a cliff. The PCIe topology QEMU exposes to the VM is virtual, so the P2P path between GPUs can be cut and degrade to relaying through the host. If P2P bandwidth is clearly limited, the likely cause is the IOMMU’s ACS policy blocking the peer-to-peer DMA path.
Verifying Passthrough Information Collection
Before running any heavy compute, confirm the state of the passed-through cards.
nvidia-smi -q | grep -E "Product Name|GPU UUID|BAR1|Memory"
Platform A: 4x RTX 3090
Product Name : NVIDIA GeForce RTX 3090
GPU UUID : GPU-1dc002ea-dc6e-5806-d798-43de15b92028
FB Memory Usage
BAR1 Memory Usage
Conf Compute Protected Memory Usage
Memory : 0 %
Memory Current Temp : N/A
Memory Max Operating Temp : N/A
GPU Memory Power Readings
Memory : 405 MHz
Memory : N/A
Memory : N/A
Memory : N/A
Memory : 9751 MHz
Product Name : NVIDIA GeForce RTX 3090
GPU UUID : GPU-5b7a34da-4cbe-86e8-9607-e6d2b336b944
FB Memory Usage
BAR1 Memory Usage
... (the other 3 cards are the same)
Platform B: 8x V100-SXM2-32GB
Product Name : Tesla V100-SXM2-32GB
GPU UUID : GPU-4a303885-0edf-7219-d89d-f863a9e11366
FB Memory Usage
BAR1 Memory Usage
Conf Compute Protected Memory Usage
Memory : 0 %
Device Memory : 0
Texture Memory : N/A
Device Memory : 0
Texture Memory : N/A
...
Memory Current Temp : 37 C
Memory Max Operating Temp : 85 C
GPU Memory Power Readings
Memory : 877 MHz
...
The difference: under passthrough both sets of cards are recognized, but the gap in monitoring between consumer and data-center cards is obvious. The RTX 3090 VBIOS does not expose core sensor data such as Memory Current Temp in an enterprise context (shown as N/A), while the enterprise V100, even virtualized, passes through ECC memory, texture cache status and exact operating temperature limits intact. That is a critical set of monitoring signals during long, high-pressure burn-in tests.
AI Training Performance Test
Preparing the Benchmark Script (train_benchmark.py)
Before the training benchmark, prepare a minimal PyTorch DDP throughput script in the virtualenv (load tensors into the GPU to saturate peak compute):
# train_benchmark.py
import torch, time, argparse, os
import torch.nn as nn
import torch.optim as optim
import torchvision.models as models
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model', default='resnet50')
parser.add_argument('--batch-size', type=int, default=128)
parser.add_argument('--epochs', type=int, default=5)
parser.add_argument('--num-gpus', type=int, default=1)
parser.add_argument('--local_rank', type=int, default=-1)
args = parser.parse_args()
local_rank = int(os.environ.get("LOCAL_RANK", args.local_rank))
is_ddp = local_rank != -1
if is_ddp:
torch.distributed.init_process_group(backend='nccl')
torch.cuda.set_device(local_rank)
device = torch.device(f"cuda:{local_rank}")
else:
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = models.resnet50().to(device)
if is_ddp:
model = nn.parallel.DistributedDataParallel(model, device_ids=[local_rank])
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
inputs = torch.randn(args.batch_size, 3, 224, 224).to(device)
targets = torch.randint(0, 1000, (args.batch_size,)).to(device)
for epoch in range(args.epochs):
torch.cuda.synchronize()
start = time.time()
for _ in range(50):
optimizer.zero_grad()
loss = criterion(model(inputs), targets)
loss.backward()
optimizer.step()
torch.cuda.synchronize()
if local_rank in [-1, 0]:
throughput = (50 * args.batch_size * (args.num_gpus if is_ddp else 1)) / (time.time() - start)
print(f"Epoch {epoch} Throughput: {throughput:.2f} images/sec")
if __name__ == '__main__':
main()
Single GPU: ResNet-50
python train_benchmark.py --model resnet50 --batch-size 128 --epochs 5 --num-gpus 1
Parameter notes:
| Parameter | Description |
|---|---|
--model resnet50 |
Uses torchvision.models.resnet50 as the reference model; ResNet-50 is the industry’s most common training throughput standard |
--batch-size 128 |
Feeds 128 224×224 images per iteration, which safely fills the 24 GB of an RTX 3090; drop to 64 if you hit an OOM |
--epochs 5 |
5 rounds of 50 forward + backward passes each; the first 1-2 rounds are warm-up and the average of the last 3 is the effective throughput |
--num-gpus 1 |
Single-GPU mode; the script does not enable DDP, so it purely measures one card’s peak compute |
During the test, open another terminal and run watch -n 1 nvidia-smi to watch GPU utilization and memory use in real time; the peaks go in the table below:
| Metric | RTX 3090 (passthrough) |
|---|---|
| Throughput (images/sec) | ~512 |
| GPU utilization (%) | 100% |
| Memory used (MB) | 12739MiB / 24576MiB |
Additional Memory Pressure Test
In the standard benchmark above, the RTX 3090’s memory utilization is only about 52% (12.7 GB / 24 GB). The GPU compute units are already saturated, but the memory mapping path has not really been verified under pressure. Under passthrough, VFIO’s DMA mappings and QEMU’s BAR address space allocation can both run into trouble at high memory usage — this kind of bug only shows up near the memory limit.
Raise the batch size step by step until OOM (out of memory) and record the last configuration that ran stably:
# Increase the batch size step by step to find the memory limit
python train_benchmark.py --model resnet50 --batch-size 256 --epochs 3 --num-gpus 1
python train_benchmark.py --model resnet50 --batch-size 384 --epochs 3 --num-gpus 1
python train_benchmark.py --model resnet50 --batch-size 512 --epochs 3 --num-gpus 1
# If 512 still does not OOM, try 640, 768...
| Metric | RTX 3090 (passthrough) |
|---|---|
| Largest stable batch size | 256 (384 OOMs) |
| Memory used | 23145 MiB / 24576 MiB (94.2%) |
| Throughput (images/sec) | ~519 |
What that largest stable batch size really means: it reflects the actual ceiling of usable GPU memory under passthrough, not the theoretical figure
nvidia-smireports. When later sizing vLLM’s--gpu-memory-utilizationand KV cache, use this rather than the card’s rated number.
The multi-GPU test uses PyTorch’s official torchrun launcher, which assigns the LOCAL_RANK environment variable to each process and initializes the NCCL communication backend.
Platform A: 4x RTX 3090
torchrun --nproc_per_node=4 train_benchmark.py --model resnet50 --batch-size 128 --epochs 5
Platform B: 8x V100
torchrun --nproc_per_node=8 train_benchmark.py --model resnet50 --batch-size 64 --epochs 5
torchrun parameter notes:
| Parameter | Description |
|---|---|
--nproc_per_node=4 |
Processes launched per machine; must equal the number of visible GPUs (4 on the RTX 3090 platform, 8 on the V100 platform) |
--batch-size 128 |
Local batch size per card; with 4 cards the global batch is 128 × 4 = 512 |
--epochs 5 |
Also 5 rounds for multi-GPU, to observe whether AllReduce synchronization drags down total throughput |
The V100 platform uses a batch size of 64 rather than 128 because the V100-32GB has high HBM2 bandwidth but fewer compute units; at batch size 128 the units spend more time waiting on memory reads, which lowers per-card utilization.
| Metric | 4x RTX 3090 (passthrough) |
|---|---|
| Per-card throughput (images/sec) | ~455 |
| Total throughput (images/sec) | ~1820 |
| Linear scaling ratio | 0.89 |
Linear scaling ratio = total multi-GPU throughput ÷ (single-GPU throughput × number of cards). The ideal is 1.0; AllReduce communication overhead pulls it below. The 3090 platform has no NVLink, so gradient synchronization goes over PCIe, and 0.89 is decent. Once I have numbers for the V100 NVLink platform, that will make a good comparison.
In DDP training, the multi-GPU throughput bottleneck comes mainly from the lack of NVLink: AllReduce gradient synchronization can only rely on PCIe, which brings substantial communication overhead. With large models or multi-GPU parallel training, that communication limit often ends up dominating performance.
LLM Inference Performance Test
LLM inference is one of the most typical workloads under GPU passthrough. Frameworks use the underlying hardware very differently, so cross-checking several of them is the only way to judge the real impact of the passthrough layer.
Test Matrix
| Model | Parameters | Precision | Memory needed | Framework |
|---|---|---|---|---|
| Qwen3.5-9B | 9B | FP16 | ~18 GB | vLLM |
| Qwen3.5-35B-A3B | 35B MoE | FP16 | ~15 GB (very few active parameters) | vLLM |
| Qwen3-Coder-Next | ~32B | FP16 | ~64 GB | vLLM |
| zai-org/GLM-5 | ~9B | FP16 | ~18 GB | vLLM |
| MiniMaxAI/MiniMax-M2.5 | MoE | FP16 | - | vLLM (multi-GPU) |
| Qwen3.5-122B-A10B | 122B MoE | FP8 / INT4 | ~60 GB (quantized) | vLLM (multi-GPU TP required) |
Model choice has to match memory capacity. The RTX 3090’s 24 GB of GDDR6X and the V100’s 16/32 GB of HBM2 differ fundamentally in bandwidth and capacity — that affects not only how large a model you can run, but directly the KV cache size and maximum concurrency.
vLLM
vLLM achieves high-throughput inference through continuous batching and PagedAttention, and is the default choice for production deployments right now.
# A pip install is fine for a temporary test environment
# 1. Switch to the Tsinghua PyPI mirror for faster installs
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip install vllm
# 2. Point HF at a domestic mirror so pulling models at startup does not hang on timeouts
export HF_ENDPOINT="https://hf-mirror.com"
# 9B, 2 GPUs
python -m vllm.entrypoints.openai.api_server \
--model Qwen/Qwen3.5-9B \
--dtype float16 \
--tensor-parallel-size 2 \
--gpu-memory-utilization 0.9 \
--max-model-len 4096 \
--port 8000
# 9B, 4 GPUs
python -m vllm.entrypoints.openai.api_server \
--model Qwen/Qwen3.5-9B \
--dtype float16 \
--tensor-parallel-size 4 \
--gpu-memory-utilization 0.9 \
--max-model-len 4096 \
--port 8000
# Multi-GPU TP=4 for the 122B MoE model
python -m vllm.entrypoints.openai.api_server \
--model Qwen/Qwen3.5-122B-A10B \
--dtype float16 \
--tensor-parallel-size 4 \
--gpu-memory-utilization 0.9 \
--max-model-len 4096 \
--port 8000
The benchmark uses vLLM’s built-in benchmark tool directly; it simulates realistic concurrent request patterns:
export HF_ENDPOINT=https://hf-mirror.com
vllm bench serve \
--backend openai \
--base-url http://localhost:8000 \
--model Qwen/Qwen3.5-9B \
--num-prompts 1000 \
--request-rate inf \
--temperature 0
Single GPU (9B model):
I did not keep the full logs for single-GPU 9B vLLM runs, so there are no numbers here. To reproduce, use vllm bench serve above with --num-prompts and --request-rate held fixed, then compare.
Multi-GPU TP=4 (9B model):
This is a 9B model split across four cards (tensor parallel size = 4) for inference. Because the model is small, forcing it across four cards usually costs more in frequent inter-GPU communication (AllReduce) than it gains in memory bandwidth; that makes it a valuable test of architectural overhead.
| Metric | 4x RTX 3090 (passthrough) |
|---|---|
| Successful concurrent requests | 1000 |
| Total Token Throughput (tokens/s) | 2404.30 |
| Generation Throughput (tokens/s) | 267.14 |
| Request Throughput (req/s) | 2.09 |
| Median TTFT (ms) | 258617.31 |
| Median TPOT (ms) | 754.74 |
Reading the numbers:
- Total Token Throughput (2404 tok/s): overall system throughput, covering both prompt processing and token generation.
- Generation Throughput (267 tok/s): how fast new tokens are actually produced. TP=4 introduces a lot of PCIe communication, and for a model as small as 9B the communication latency (ITL ~747ms) is severe, so real generation speed is not high.
- Median TTFT (258s): time to first token. Under the extreme
--request-rate inf(1000 requests at once), the request that queued longest waited over four minutes for its first token, which shows the PagedAttention scheduling pressure at extreme load.
Multi-GPU TP (122B model):
I did not finish a full benchmark on the 122B MoE model, so there are no numbers here. Configuration-wise, four 3090s need INT4/FP8 quantization and a TP=4 split; measure the memory and concurrency limits in your own environment.
GPU Stress and Stability Testing
Stability under passthrough deserves more attention than performance. A GPU that runs 24 hours on bare metal is not necessarily stable once passed through — VFIO’s DMA mappings, the IOMMU translation tables and QEMU interrupt routing are all potential failure points. A long burn-in with gpu-burn, plus continuous end-to-end monitoring with Prometheus + Grafana + DCGM, is what gives a trustworthy stability verdict.
Compiling gpu-burn
git clone https://github.com/wilicc/gpu-burn.git
cd gpu-burn
make CUDAPATH=/usr/local/cuda
./gpu_burn 10 # run 10 seconds first as a check
gpu-burn runs large matrix multiplications on every visible GPU in parallel and periodically verifies the results. FAULTY in the output means a result did not match — possible causes include physical memory defects, bit flips from overheating, and unstable PCIe links. That is not rare on second-hand mining cards or V100s that have run under heavy load for a long time.
Monitoring Stack: Prometheus + Grafana + DCGM Exporter
Running gpu-burn alone only tells you “pass” or “fail”, not “why”. The fine-grained time-series data DCGM Exporter collects (temperature curves, power draw, clock changes, XID errors, PCIe replay counts) is what lets you find the root cause.
graph TB
subgraph Visualization["Visualization layer"]
GRAFANA["Grafana (:3000)<br/>GPU Monitoring Dashboard"]
end
subgraph Collection["Data collection and storage"]
PROM["Prometheus (:9090)<br/>time-series scrape and storage (5s / 15s interval)"]
end
subgraph Exporters["Metric exporters"]
DCGM["dcgm-exporter (:9400)<br/>GPU metrics"]
NODE["node_exporter (:9100)<br/>system metrics"]
end
GRAFANA -->|"PromQL queries"| PROM
PROM -->|"scrape"| DCGM
PROM -->|"scrape"| NODE
DCGM Exporter
DCGM (Data Center GPU Manager) is NVIDIA’s data-center GPU management framework, with richer metrics and lower collection overhead than nvidia-smi.
Docker deployment (recommended):
docker run -d --gpus all --restart always \
--name dcgm-exporter \
-p 9400:9400 \
nvcr.io/nvidia/k8s/dcgm-exporter:3.3.8-3.6.0-debian12
curl -s http://localhost:9400/metrics | head -20
Bare-metal install (no Docker):
# Option A: full DCGM install
apt install -y datacenter-gpu-manager
nv-hostengine
dcgmi discovery
# Option B: lightweight nvidia_gpu_exporter (nvidia-smi only)
wget https://github.com/utkuozdemir/nvidia_gpu_exporter/releases/download/v1.2.1/nvidia-gpu-exporter_1.2.1_linux_amd64.tar.gz
tar -xzf nvidia-gpu-exporter_1.2.1_linux_amd64.tar.gz
./nvidia_gpu_exporter --web.listen-address=":9835" &
Key DCGM metrics:
| Metric | Description | Unit | Meaning during burn-in |
|---|---|---|---|
DCGM_FI_DEV_GPU_TEMP |
GPU core temperature | °C | Whether cooling is adequate |
DCGM_FI_DEV_GPU_UTIL |
GPU utilization | % | Should stay around 100% |
DCGM_FI_DEV_POWER_USAGE |
Instantaneous power draw | W | Whether it reaches the TDP limit |
DCGM_FI_DEV_SM_CLOCK |
SM clock | MHz | Direct evidence of throttling |
DCGM_FI_DEV_POWER_VIOLATION |
Time spent power-limited | us | Non-zero means the power limit is capping performance |
DCGM_FI_DEV_THERMAL_VIOLATION |
Time spent thermally limited | us | Non-zero means the thermal limit is capping performance |
DCGM_FI_DEV_XID_ERRORS |
XID error count | count | Non-zero means a fault |
DCGM_FI_DEV_PCIE_REPLAY_COUNTER |
PCIe replay count | count | Reflects PCIe link signal quality |
Node Exporter + Prometheus + Grafana
# Node Exporter
docker run -d --restart always \
--name node-exporter \
--net="host" --pid="host" \
-v "/:/host:ro,rslave" \
quay.io/prometheus/node-exporter:latest \
--path.rootfs=/host
Prometheus configuration at /opt/monitoring/prometheus/prometheus.yml:
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'dcgm-exporter'
scrape_interval: 5s # shorter scrape interval for GPU metrics
static_configs:
- targets: ['localhost:9400']
- job_name: 'node-exporter'
static_configs:
- targets: ['localhost:9100']
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
# Prometheus
docker run -d --restart always \
--name prometheus \
--net="host" \
-v /opt/monitoring/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml \
-v /opt/monitoring/prometheus/data:/prometheus \
prom/prometheus:latest \
--config.file=/etc/prometheus/prometheus.yml \
--storage.tsdb.path=/prometheus \
--storage.tsdb.retention.time=30d \
--web.enable-lifecycle
# Grafana
mkdir -p /opt/monitoring/grafana
docker run -d --restart always \
--name grafana \
--net="host" \
-v /opt/monitoring/grafana:/var/lib/grafana \
-e "GF_SECURITY_ADMIN_PASSWORD=admin" \
grafana/grafana:latest
Import the official DCGM dashboard into Grafana (ID: 12239), then customize panels as needed. The PromQL queries that matter during burn-in:
# Temperature trend
DCGM_FI_DEV_GPU_TEMP{job="dcgm-exporter"}
# SM clock throttling
DCGM_FI_DEV_SM_CLOCK{job="dcgm-exporter"}
# How often the power limit trips
rate(DCGM_FI_DEV_POWER_VIOLATION{job="dcgm-exporter"}[1m])
# XID errors (any non-zero is a red flag)
DCGM_FI_DEV_XID_ERRORS{job="dcgm-exporter"}
# PCIe replay error trend
DCGM_FI_DEV_PCIE_REPLAY_COUNTER{job="dcgm-exporter"}
Alert rules: GPU temperature > 85°C, XID errors > 0, sustained throttling > 5 minutes — those three cover most of the scenarios that make a burn-in fail.
Docker Compose One-Shot Deployment
If you deploy this repeatedly across several machines, Compose is more efficient:
# /opt/monitoring/docker-compose.yml
version: '3.8'
services:
dcgm-exporter:
image: nvcr.io/nvidia/k8s/dcgm-exporter:3.3.8-3.6.0-debian12
restart: always
deploy:
resources:
reservations:
devices:
- capabilities: [gpu]
ports:
- "9400:9400"
node-exporter:
image: quay.io/prometheus/node-exporter:latest
restart: always
network_mode: host
pid: host
volumes:
- /:/host:ro,rslave
command:
- '--path.rootfs=/host'
prometheus:
image: prom/prometheus:latest
restart: always
network_mode: host
volumes:
- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
- ./prometheus/data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
- '--storage.tsdb.retention.time=30d'
- '--web.enable-lifecycle'
grafana:
image: grafana/grafana:latest
restart: always
network_mode: host
volumes:
- ./grafana:/var/lib/grafana
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
cd /opt/monitoring && docker compose up -d
Running the Burn-In
Work up in stages, lengthening the load each time:
| Stage | Duration | What it verifies |
|---|---|---|
| Warm-up | 60s | VFIO binding works, gpu-burn starts, every GPU is loaded |
| Short stress | 10min | Whether temperatures settle into a steady state within a reasonable range |
| Medium load | 1h | Throttling behavior and power-limit behavior under sustained load |
| Long burn-in | 8-24h | Intermittent memory errors, PCIe link degradation, problems that build up with heat |
./gpu_burn 60 # warm-up
./gpu_burn 600 # short
./gpu_burn 3600 # medium
# Run the long burn-in inside tmux
tmux new -s gpuburn
./gpu_burn 28800
Alongside it, real-time monitoring and logging in the terminal:
# Watch in real time
watch -n 1 nvidia-smi
# Structured logging
while true; do
echo "=== $(date) ==="
nvidia-smi --query-gpu=timestamp,name,gpu_bus_id,temperature.gpu,utilization.gpu,utilization.memory,power.draw,clocks.sm,clocks.mem,memory.used,memory.total,pcie.link.gen.current,pcie.link.width.current --format=csv
sleep 5
done | tee gpu_burn_log_$(date +%Y%m%d_%H%M%S).csv
# Full DCGM diagnostics (run once after the burn-in)
dcgmi diag -r 3
Burn-In Results
The 8-hour burn-in did not finish, so there are no temperature or power numbers here. To reproduce, run the staged commands above and keep the nvidia-smi CSV logs; below are the criteria for judging the result.
Stability Criteria
| Check | Pass | Watch | Fail |
|---|---|---|---|
| Steady-state GPU temperature | < 83°C | 83-89°C (check airflow/heatsink) | >= 90°C (overheating; must fix before production) |
| Throttling | None | Occasional (< 5% of time) | Sustained (> 10% of time) |
| XID errors | 0 | — | > 0 (hardware or driver fault) |
| PCIe replay errors | 0 | 1-10 (possibly signal jitter) | > 10 (check PCIe riser/cable/switch) |
| gpu-burn FAULTY | 0 | — | > 0 (memory or compute unit fault) |
| Power limit | Occasional (normal) | Frequent (check TDP config) | Sustained (lower the power limit or improve power delivery) |
Model Serving Deployment Architecture
Once passthrough works and the benchmarks pass, the real problems start: GPU allocation with several models in play, request routing, access control and observability. This section goes straight to a production-oriented design — a LiteLLM gateway as the single entry point, with security built in rather than bolted on.
Overall Architecture
graph TB
subgraph Clients["Callers"]
OPENCLAW["OpenClaw Agent"]
WEBAPP["Web app"]
API_USER["API caller"]
end
subgraph Gateway["LLM gateway layer (VLAN 20)"]
TLS["TLS termination<br/>Caddy / Nginx"]
LITE["LiteLLM Proxy<br/>:4000"]
TLS --> LITE
end
subgraph GPU_VM["GPU inference layer (VLAN 20)"]
V1["vLLM :8001<br/>Llama-3.1-8B<br/>GPU 0 · fast"]
V2["vLLM :8002<br/>Qwen2.5-14B<br/>GPU 1 · balanced"]
V3["vLLM :8003<br/>DeepSeek-R1-32B<br/>GPU 2-3 · reasoning"]
end
subgraph Fallback["External fallback"]
CLAUDE["Claude API"]
end
subgraph Observability["Observability"]
LANGFUSE["Langfuse<br/>Tracing + audit"]
PROM_OBS["Prometheus<br/>+ Grafana"]
end
Clients -->|"HTTPS + API Key"| TLS
LITE --> V1
LITE --> V2
LITE --> V3
LITE -->|"Fallback"| CLAUDE
LITE -->|"Callback"| LANGFUSE
GPU_VM --> PROM_OBS
Architecture points:
- Every caller talks only to the LiteLLM gateway — vLLM backend ports are not exposed, and auth, rate limiting and auditing all happen at one point, the gateway
- TLS terminates in front of the gateway — API keys and inference content never travel in plaintext
- The vLLM backends and the gateway sit in the same VLAN — callers (OpenClaw / Web App) are in another VLAN, and the firewall only allows the gateway port
GPU Allocation Strategy
The core principle for GPU allocation: split cards by model weights and concurrency needs, not evenly.
Platform A (4x RTX 3090, 24GB each):
| GPU | Model | Quantization | Memory | Role |
|---|---|---|---|---|
| GPU 0 | Llama-3.1-8B-Instruct | FP16 | ~16 GB | fast — everyday chat, translation, formatting |
| GPU 1 | Qwen2.5-14B-Chat | INT4 (GPTQ) | ~8 GB | balanced — content generation, technical Q&A |
| GPU 2-3 | DeepSeek-R1-Distill-Qwen-32B | INT4 (AWQ), TP=2 | ~10 GB/card | reasoning — code review, complex reasoning |
Platform B (8x V100-32GB):
| GPU | Model | Quantization | Memory | Role |
|---|---|---|---|---|
| GPU 0 | Llama-3.1-8B-Instruct | FP16 | ~16 GB | fast |
| GPU 1-2 | Qwen2.5-14B-Chat | FP16, TP=2 | ~14 GB/card | balanced |
| GPU 3-6 | Llama-3.1-70B-Instruct | INT4 (AWQ), TP=4 | ~10 GB/card | reasoning |
| GPU 7 | Embedding / Reranker | FP16 | ~4 GB | embedding — RAG scenarios |
Model Download and Authentication (Hugging Face)
In production, or in a server room without decent outbound access, do not let vLLM pull model layers at startup. Downloading the models ahead of time is more reliable. For gated models like Llama-3.1 in particular, you must request access on the Hugging Face website and supply an HF_TOKEN before you can download.
- Get an access token on Hugging Face (the Read role is enough)
- Export the environment variables and download with the native tool at high concurrency:
# Install the official HF CLI
pip install -U "huggingface_hub[cli]"
# Export the environment variables
export HF_TOKEN="hf_xxxxx_your_token_xxxxx"
# Use a domestic mirror to avoid timeouts reaching huggingface.co
export HF_ENDPOINT="https://hf-mirror.com"
# Set a single download directory (for example a fast NVMe mount)
export HF_HOME="/data/llm/models"
# Download fast with the CLI (resumable)
# Llama-3.1 is a gated model and needs HF_TOKEN to download
hf download Qwen/Qwen3.5-9B
hf download Qwen/Qwen3.5-35B-A3B
hf download Qwen/Qwen3-Coder-Next
hf download zai-org/GLM-5
hf download MiniMaxAI/MiniMax-M2.5
hf download Qwen/Qwen3.5-122B-A10B
With a local cache, vLLM still starts in seconds even without a network.
Docker Environment Setup
In production, vLLM must be deployed in containers rather than from a bare pip install — the latter gives no isolation, version pinning or process management. First install Docker Engine and the NVIDIA Container Toolkit on the GPU VM:
# Use the official install script, sped up through the Tsinghua mirror
export DOWNLOAD_URL="https://mirrors.tuna.tsinghua.edu.cn/docker-ce"
curl -fsSL https://get.docker.com | sh
# Install the NVIDIA Container Toolkit (so Docker can access the passed-through GPUs)
apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
curl \
gnupg2
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \
&& curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \
tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
export NVIDIA_CONTAINER_TOOLKIT_VERSION=1.18.2-1
apt-get install -y \
nvidia-container-toolkit=${NVIDIA_CONTAINER_TOOLKIT_VERSION} \
nvidia-container-toolkit-base=${NVIDIA_CONTAINER_TOOLKIT_VERSION} \
libnvidia-container-tools=${NVIDIA_CONTAINER_TOOLKIT_VERSION} \
libnvidia-container1=${NVIDIA_CONTAINER_TOOLKIT_VERSION}
nvidia-ctk runtime configure --runtime=docker
systemctl restart docker
# Verify the GPU is visible inside a container
docker run --rm --gpus all hub.infra.plz.ac/nvidia/cuda:12.4.0-base-ubuntu22.04 nvidia-smi
Starting the vLLM Backends
Manage all vLLM inference instances with Docker Compose (bound to localhost only, not exposed):
# /opt/llm-inference/docker-compose.yml
services:
vllm-fast:
image: vllm/vllm-openai:latest
restart: always
ipc: host
ports:
- "127.0.0.1:8001:8000"
volumes:
- /data/llm/models:/root/.cache/huggingface
environment:
- HF_ENDPOINT=https://hf-mirror.com
- TRANSFORMERS_OFFLINE=1
deploy:
resources:
reservations:
devices:
- driver: nvidia
device_ids: ['0']
capabilities: [gpu]
command: >
--model Qwen/Qwen3.5-9B
--dtype float16
--gpu-memory-utilization 0.9
--max-model-len 4096
--port 8000
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
vllm-balanced:
image: vllm/vllm-openai:latest
restart: always
ipc: host
ports:
- "127.0.0.1:8002:8000"
volumes:
- /data/llm/models:/root/.cache/huggingface
environment:
- HF_ENDPOINT=https://hf-mirror.com
- TRANSFORMERS_OFFLINE=1
deploy:
resources:
reservations:
devices:
- driver: nvidia
device_ids: ['1']
capabilities: [gpu]
command: >
--model Qwen/Qwen3.5-35B-A3B
--dtype float16
--gpu-memory-utilization 0.9
--max-model-len 4096
--port 8000
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
vllm-reasoning:
image: vllm/vllm-openai:latest
restart: always
ipc: host
ports:
- "127.0.0.1:8003:8000"
volumes:
- /data/llm/models:/root/.cache/huggingface
environment:
- HF_ENDPOINT=https://hf-mirror.com
- TRANSFORMERS_OFFLINE=1
deploy:
resources:
reservations:
devices:
- driver: nvidia
device_ids: ['2', '3']
capabilities: [gpu]
command: >
--model Qwen/Qwen3.5-122B-A10B
--dtype float16
--tensor-parallel-size 2
--gpu-memory-utilization 0.9
--max-model-len 8192
--port 8000
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
cd /opt/llm-inference && docker compose up -d
# Verify all instances are healthy
docker compose ps
curl -s http://127.0.0.1:8001/health
curl -s http://127.0.0.1:8002/health
curl -s http://127.0.0.1:8003/health
The
127.0.0.1:800x:8000port mapping keeps vLLM listening on loopback only.restart: always+healthcheckgives process-level self-healing: a crashed container restarts automatically, and a failed health check marks it unhealthy so LiteLLM can take it out of rotation.
LiteLLM as the single entry point handles model routing, API key auth, rate limiting, fallback and auditing.
# /opt/llm-gateway/litellm_config.yaml
model_list:
- model_name: "fast"
litellm_params:
model: "openai/meta-llama/Llama-3.1-8B-Instruct"
api_base: "http://127.0.0.1:8001/v1"
api_key: "not-used"
- model_name: "balanced"
litellm_params:
model: "openai/Qwen/Qwen2.5-14B-Chat-GPTQ-Int4"
api_base: "http://127.0.0.1:8002/v1"
api_key: "not-used"
- model_name: "reasoning"
litellm_params:
model: "openai/deepseek-ai/DeepSeek-R1-Distill-Qwen-32B"
api_base: "http://127.0.0.1:8003/v1"
api_key: "not-used"
# External fallback: degrade automatically when local reasoning is unavailable
- model_name: "reasoning"
litellm_params:
model: "claude-sonnet-4-20250514"
api_key: "${ANTHROPIC_API_KEY}"
router_settings:
routing_strategy: "simple-shuffle"
num_retries: 2
timeout: 300
allowed_fails: 3 # remove a backend temporarily after 3 consecutive failures
general_settings:
master_key: "${LITELLM_MASTER_KEY}"
database_url: "sqlite:///litellm.db"
allow_user_auth: true
litellm_settings:
max_budget: 100
budget_duration: "monthly"
success_callback: ["langfuse"] # per-request tracing
store_model_in_db: true # persist audit logs
The same model name
reasoningdefines two backends (local vLLM + Claude API). LiteLLM prefers the local instance and falls back to Claude after repeated failures.
Access Control
Multi-Level API Keys
Each caller gets a key with different permissions — there is no omnipotent key with unlimited access:
# OpenClaw agent — all three models, $50 monthly budget
curl -X POST http://localhost:4000/key/generate \
-H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \
-d '{
"key_alias": "openclaw-agent",
"models": ["fast", "balanced", "reasoning"],
"max_budget": 50, "budget_duration": "monthly",
"max_parallel_requests": 5,
"tpm_limit": 100000, "rpm_limit": 60
}'
# Web app — fast only, $10 monthly budget
curl -X POST http://localhost:4000/key/generate \
-H "Authorization: Bearer ${LITELLM_MASTER_KEY}" \
-d '{
"key_alias": "webapp-chatbot",
"models": ["fast"],
"max_budget": 10, "budget_duration": "monthly",
"max_parallel_requests": 10,
"tpm_limit": 50000, "rpm_limit": 100
}'
| Control | OpenClaw key | Web app key |
|---|---|---|
| Available models | fast, balanced, reasoning | fast only |
| Monthly budget | $50 | $10 |
| Max concurrency | 5 | 10 |
| TPM limit | 100K | 50K |
| RPM limit | 60 | 100 |
TLS + mTLS
# Caddy handles TLS termination in one line (self-signed or ACME)
caddy reverse-proxy --from llm.internal:443 --to localhost:4000
Where the internal network has its own CA, use mTLS for mutual authentication:
server {
listen 443 ssl;
server_name llm.internal;
ssl_certificate /etc/ssl/llm-gateway.crt;
ssl_certificate_key /etc/ssl/llm-gateway.key;
ssl_client_certificate /etc/ssl/ca.crt;
ssl_verify_client on;
location / {
proxy_pass http://127.0.0.1:4000;
proxy_read_timeout 600s;
}
}
Network Isolation
graph LR
subgraph VLAN20["VLAN 20 — AI inference network"]
VLLM["vLLM (127.0.0.1 only)"]
LITELLM_GW["LiteLLM Gateway"]
VLLM ---|"localhost"| LITELLM_GW
end
subgraph VLAN30["VLAN 30 — application network"]
OC["OpenClaw"]
WA["Web App"]
end
subgraph VLAN10["VLAN 10 — management network"]
ADM["Admin workstation"]
end
OC -->|"only :443"| LITELLM_GW
WA -->|"only :443"| LITELLM_GW
ADM -->|"SSH + Grafana"| VLLM
| Rule | Source → target | Port | Notes |
|---|---|---|---|
| Allow | VLAN 30 → LiteLLM | 443 | Callers can only go through the gateway |
| Allow | VLAN 10 → GPU VM | 22, 3000, 9090 | Operations management |
| Deny | VLAN 30 → vLLM | 8001-8003 | No bypassing the gateway |
| Deny | * → GPU VM | * | Default deny |
Langfuse Observability and Tracing
In a multi-model, multi-agent architecture, Prometheus watching GPU hardware metrics (utilization, memory, power) is not enough. At the application layer you need to know what each prompt actually looked like, what the model replied with, at which step a generation refused to answer, and what each agent’s real token spend is.
Langfuse is the go-to open-source LLM observability platform right now, and it integrates with the LiteLLM gateway seamlessly.
Deploying the Langfuse Platform
Bring up the Langfuse infrastructure separately on the management network (VLAN 10) with Docker Compose:
# docker-compose.langfuse.yml
version: '3.8'
services:
langfuse-server:
image: langfuse/langfuse:2
depends_on:
- db
ports:
- "3000:3000"
environment:
- DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres
- NEXTAUTH_SECRET=my_secure_secret
- SALT=my_secure_salt
- NEXTAUTH_URL=http://192.168.1.14:3000
- TELEMETRY_ENABLED=false
db:
image: postgres:15
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=postgres
volumes:
- langfuse_data:/var/lib/postgresql/data
volumes:
langfuse_data:
Non-Invasive LiteLLM Integration
LiteLLM integrates Langfuse natively and deeply. Give the LiteLLM Gateway the credentials, and it intercepts and uploads all request metadata automatically, with no code changes in OpenClaw or the web app.
Add the Langfuse API keys to LiteLLM’s environment:
# Set before starting LiteLLM (or in the systemd service file)
export LANGFUSE_PUBLIC_KEY="pk-lf-..."
export LANGFUSE_SECRET_KEY="sk-lf-..."
# Point at the Langfuse address you just deployed
export LANGFUSE_HOST="http://192.168.1.14:3000"
Make sure callbacks are enabled in litellm_config.yaml:
litellm_settings:
success_callback: ["langfuse"]
failure_callback: ["langfuse"]
Core Debugging Capabilities for Agent Scenarios
Once connected, conversations from either the web app or the OpenClaw agent give you these application-level views in the Langfuse console:
- Generation Replay: see the original request headers, system prompt, tool definitions and final response in full. With an OpenClaw agent the context it assembles is very complex, so when a prompt injection gets through, this is the crucial evidence on record.
- Latency Breakdown: Langfuse splits streaming requests precisely into Time-to-First-Token (TTFT) and Tokens-per-Second. A sudden spike in TTFT usually means severe PagedAttention K-V cache fragmentation in vLLM or requests queueing up; a collapse in generation speed can be checked through replay to see whether it hit a complex reasoning response.
- Cost by User/Key: since OpenClaw and the web app got different LiteLLM keys above, Langfuse maps and groups them by key ID automatically. You can see at a glance how many requests and tokens each caller consumes per day, and combine that with budgets for closed-loop FinOps management.
Dynamic Model Scheduling (Optional)
The design above is “one GPU per model, resident in memory” — suitable when the number of models is <= the number of GPUs. When there are more models than GPUs, you need dynamic scheduling.
vLLM LoRA Dynamic Loading
For one base model plus several LoRA adapters, vLLM natively supports hot-swapping LoRAs with no extra instances:
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Llama-3.1-8B-Instruct \
--enable-lora \
--lora-modules \
code-assistant=./lora-adapters/code \
translator=./lora-adapters/translator \
summarizer=./lora-adapters/summarizer \
--max-loras 3 --max-lora-rank 16 \
--host 127.0.0.1 --port 8001
LoRA adapters are only tens of MB, so switching costs almost nothing. It suits companies where several departments share one base model but need different domain capabilities.
Ray Serve Elastic Scheduling
When you have plenty of GPUs (8x V100, say) and need fine-grained resource management:
# serve_app.py
from ray import serve
from vllm import LLM, SamplingParams
@serve.deployment(num_replicas=1, ray_actor_options={"num_gpus": 1})
class LLMDeployment:
def __init__(self, model_name: str):
self.llm = LLM(model=model_name, dtype="float16", gpu_memory_utilization=0.9)
async def generate(self, prompt: str, max_tokens: int = 512):
params = SamplingParams(max_tokens=max_tokens)
outputs = self.llm.generate([prompt], params)
return outputs[0].outputs[0].text
light = LLMDeployment.bind("meta-llama/Llama-3.1-8B-Instruct")
heavy = LLMDeployment.bind("deepseek-ai/DeepSeek-R1-Distill-Qwen-32B")
Ray Serve supports fractional GPU allocation (0.5 GPU for a small model, for example), autoscaling on request volume and cross-node scheduling. The cost is the operational complexity of a Ray cluster — not worth it at four cards, worth considering at eight or more.
OpenClaw Integration
Wiring the inference cluster above into OpenClaw makes it route models automatically by task complexity.
Architecture
graph TB
subgraph Access["Message channels"]
TG["Telegram Bot"]
WEB["Control UI"]
end
subgraph Agent["OpenClaw (VLAN 30)"]
GW["Gateway :18789"]
PI["Agent instance"]
SANDBOX["Docker Sandbox"]
SKILL["Skills<br/>model-router"]
end
subgraph LLM["LLM gateway (VLAN 20)"]
LITE["LiteLLM :443<br/>TLS + key auth"]
end
subgraph GPUs["GPU inference (VLAN 20)"]
F["fast<br/>8B"]
B["balanced<br/>14B"]
R["reasoning<br/>32B"]
end
TG --> GW
WEB --> GW
GW --> PI
PI --> SANDBOX
PI --> SKILL
PI -->|"sk-openclaw-xxx"| LITE
LITE --> F
LITE --> B
LITE --> R
OpenClaw Configuration
{
"models": {
"providers": {
"gpu-cluster": {
"type": "openai-compatible",
"baseUrl": "https://llm.internal/v1",
"apiKey": "${LITELLM_API_KEY}",
"models": [
{ "id": "fast", "name": "Fast response (8B)", "contextLength": 4096 },
{ "id": "balanced", "name": "Balanced (14B)", "contextLength": 4096 },
{ "id": "reasoning", "name": "Deep reasoning (32B)", "contextLength": 8192 }
]
}
}
},
"agents": {
"defaults": {
"model": "gpu-cluster:fast"
}
},
"tools": {
"profile": "messaging",
"deny": ["group:automation", "group:runtime"],
"exec": { "security": "deny", "ask": "always" },
"elevated": { "enabled": false }
},
"channels": {
"telegram": {
"dmPolicy": "pairing",
"groups": { "*": { "requireMention": true } }
}
}
}
Automatic Model Routing Skill
A skill lets the agent switch models by task type, with no manual /model from the user:
<!-- ~/.openclaw/skills/model-router/SKILL.md -->
---
name: model-router
description: Automatically select an LLM model based on task complexity
---
## Model selection rules
Choose a model according to these rules; no need to ask the user before switching:
1. **Simple tasks** (translation, format conversion, casual chat, summarization) → `gpu-cluster:fast`
2. **Medium tasks** (technical Q&A, content creation, documentation) → `gpu-cluster:balanced`
3. **Complex tasks** (code review, mathematical reasoning, architecture design, multi-step analysis) → `gpu-cluster:reasoning`
Use the `/model` command to switch. If unsure about complexity, default to `balanced`.
Security Defenses
The threat model in a multi-model + agent setup is prompt injection → model privilege escalation → command execution. None of the three defensive layers can be skipped:
| Layer | Where | Measure |
|---|---|---|
| Model permissions | LiteLLM key | models allowlist — the agent can only call models it is authorized for |
| Execution permissions | OpenClaw tools |
exec.security: "deny" + elevated: false — even if the model output contains a dangerous command, it is not executed |
| Resource backstop | LiteLLM key | max_budget + rpm_limit — runaway loops caused by prompt injection have a ceiling |
| Audit trail | LiteLLM + Langfuse + OpenClaw session | Full request chain: who → which key → which model → how many tokens |
| Network isolation | VLAN + firewall | The agent cannot bypass the gateway to reach vLLM, narrowing the attack surface to the API layer |
Even if an attacker successfully injects a malicious prompt that makes the agent switch to the
reasoningmodel and produce anrm -rf /command: LiteLLM’s RPM limit stops bulk requests; OpenClaw’sexec.security: "deny"blocks execution; andmax_budgetmeans a full night of abuse still costs at most $50.
Troubleshooting Guide
GPU Initialization Failure
Symptom: inside the VM, nvidia-smi reports No devices found or NVIDIA-SMI has failed
Where to look:
# 1. On the host: confirm the VFIO binding
lspci -nnk -s <BDF>
# Expect: Kernel driver in use: vfio-pci
# 2. Host dmesg
dmesg | grep -i vfio
dmesg | grep -i nvidia
# 3. VM configuration
grep hostpci /etc/pve/qemu-server/<VMID>.conf
Common root causes, most frequent first:
- The NVIDIA driver grabbed the GPU on the host before VFIO — check module load order in the initramfs
- IOMMU grouping — another device in the same group is not bound
- Above 4G Decoding is off — BAR allocation fails
Code 43caused by ReBAR — turn off Resizable BAR in the BIOS
Host Black Screen Without Onboard Graphics
This is not a bug; it is expected. No framebuffer device means no picture.
Workarounds:
- IPMI: the most reliable out-of-band management
- SSH: all you need is a correct network configuration
- PVE Web UI:
https://<PVE_IP>:8006
Incomplete Multi-GPU Passthrough
Symptom: four GPUs are passed through, but the VM only sees two or three
# Check VFIO status card by card
for dev in $(lspci -nn | grep NVIDIA | awk '{print $1}'); do
echo "=== $dev ==="
lspci -nnk -s $dev
done
Most likely an IOMMU grouping issue, or a wrong hostpci address in the VM config file. Also check that every hostpci line in qm.conf is parsed correctly (PVE sometimes ignores lines silently because of formatting).
GPU Reset Bug
Symptom: after the VM is shut down and started again, the GPU will not initialize and the host has to be rebooted
NVIDIA GPUs do not implement FLR (Function Level Reset) perfectly, and some models cannot be reset cleanly back to their initial state after a VM shuts down. Mitigations:
- Use the
vendor-resetkernel module (effective for AMD GPUs, limited for NVIDIA) - PVE kernel 6.x+ improves NVIDIA FLR handling
- Shut the VM down with ACPI shutdown (QEMU Guest Agent) instead of
stop/reset
Performance Anomalies
What to check, from cheapest to most involved:
- PCIe link degradation:
lspci -vvv | grep -i lnkstato confirm the link speed and width match expectations - Wrong NUMA affinity: the GPU is on NUMA node 0 while the VM’s vCPUs are pinned to node 1 — cross-NUMA memory access latency doubles
- Hugepages not enabled: QEMU uses 4K pages by default, so the TLB miss rate is high
- Host CPU governor: check whether
scaling_governoris set toperformance
Performance Tuning
NUMA Affinity
The key to GPU passthrough performance is the shortest data path — GPU, memory and CPU must sit in the same NUMA domain.
# Which NUMA node the GPU belongs to
cat /sys/bus/pci/devices/0000:41:00.0/numa_node
# System NUMA topology
numactl -H
VM configuration:
# /etc/pve/qemu-server/<VMID>.conf
cpu: host
cores: 16
numa: 1
cpuunits: 10000
The ideal is to pin vCPUs to physical cores on the same side as the GPU and allocate memory from the same NUMA node. This matters especially on dual-socket platforms — the cross-socket latency penalty is usually 50-100ns.
Hugepages
# Host
echo "vm.nr_hugepages = 16384" >> /etc/sysctl.conf
sysctl -p
# VM configuration
# /etc/pve/qemu-server/<VMID>.conf
hugepages: 1024
Hugepages reduce TLB misses in the QEMU process, which matters a lot for large-memory VMs (GPU workloads usually get 64-128 GB).
PCIe ACS Override
pcie_acs_override=downstream,multifunction is already configured in the GRUB parameters. On its security impact: ACS override bypasses PCIe Access Control Services, which means devices under the same PCIe switch no longer have hardware-level DMA isolation. In a single-tenant case (all GPUs to one VM) that is entirely acceptable; in a multi-tenant case, weigh the risk.
Conclusion
Summary and Recommendations
After this round, the 4x RTX 3090 platform has passthrough configured under PVE, VFIO binding done, and PyTorch training and vLLM inference measured; for the V100 platform I have the configuration differences written down, but no performance data yet, so I cannot compare it numerically with the 3090.
- RTX 3090 platform (no onboard graphics): with SSH + Web UI management kept, passing all four cards to one Debian 13 VM works; single-card ResNet-50 is about 512 images/sec, 4-card DDP total throughput about 1820 images/sec, with a linear scaling ratio of 0.89.
- V100 platform (dual-socket NUMA): the configuration differences are laid out, with the IOMMU grouping and NUMA binding notes above; 8-GPU training, inference and long burn-in data have not been collected yet and will come later.
Passthrough itself is fairly mature on current kernels (6.x+) and QEMU, but “it runs” and “it runs stably” are two different things. IOMMU grouping, NUMA affinity, hugepages and monitoring have to be set up together; getting observability and the model gateway solid is worth more than chasing the last bit of bandwidth loss.
Next Steps
- Evaluate vGPU options (NVIDIA vGPU License / SR-IOV MIG)
- How different PVE kernel versions affect passthrough stability
- Windows VM passthrough and Anti-VM Detection
- Deploying the K8s GPU Operator inside a passthrough VM
- Fill in training, inference and 8-hour burn-in data for the V100 platform
References
- Proxmox VE PCI Passthrough documentation
- VFIO Tips and Tricks
- Arch Wiki - PCI passthrough via OVMF
- NVIDIA CUDA Toolkit Documentation
- gpu-burn - GPU stress test
- NVIDIA DCGM Documentation
- dcgm-exporter GitHub
- Grafana DCGM Dashboard
- vLLM Documentation
- LiteLLM Documentation
- Ray Serve Documentation
- OpenClaw Documentation
- Langfuse - LLM Observability
Comments