Just four years after the first release of ChatGPT by OpenAI, there is no question that LLM-assisted development has forever changed daily engineering life. Up until recently, getting strong coding results meant relying on expensive (closed-weight) frontier models. But the latest releases of open-weight models appear to be closing the gap (e.g., see here). While frontier models remain the default go-to solution for many teams, open-weight models are increasingly being considered as a legitimate alternative — whether accessed through third-party inference APIs (such as Amazon Bedrock) at lower costs, or self-hosted on your own GPUs (e.g., see here).
There are many motivations for considering self-hosting open-weight models — beyond just token cost:
-
Sensitive code and IP: Keeping sensitive code and documentation inside your own environment rather than sending it out to external APIs.
-
New workflows like continuous self-improvement (CSI): When you aren’t paying per token to a third-party service you can experiment with workflows like autonomous and continuous self-improvement loops that would otherwise be prohibitively expensive.
-
Heavy token volume: Large context windows (e.g., running on large code bases) and long reasoning sequences can quickly escalate costs when usage is heavy.
-
Custom or fine-tuned models: Running customized models (e.g., fine-tuned checkpoints or a specific setup that external providers don’t host).
On paper, self-hosting open-weight models sounds like an easy way to save money compared to frontier models or third-party APIs. Unfortunately, in practice, it is often not that simple. Self-hosting typically involves non-trivial costs including the GPU infrastructure overhead and the engineering effort required to set up and maintain the inference endpoints. At the same time, the API prices of frontier models keep dropping, as they undergo continuous improvement and optimization. Complicating the economics further is the fact that the utilization of LLM servers tends to be bursty — resulting in expensive GPUs sitting idle between requests or outside work hours. (See here for additional considerations.)
In this post, we explore the possibility of increasing the value opportunity of self-hosted LLMs by running them alongside other GPU workloads on the same GPU infrastructure. Consider the case where you have an AI/ML training workload which tends to run for extended periods and be less sensitive to occasional hiccups or minor slowdowns. What if, rather than using a dedicated GPU setup for each one, we could run both the LLM and the training job on the same machine(s)?
Naturally, the need to share refree lunches.) The LLM latency could increase and its capacity to support multiple clients could decrease. The training throughput (e.g., samples per second) could drop as could the maximum supported batch size. The question is: Could such limitations be acceptable?
Of course, the answer depends on many factors including the details of the workloads and their purposes, the specifics of the imposed limitations, and the potential impact on user experience. In this post we focus on demonstrating the technical feasibility and potential of a two-workload setup. We leave the decision regarding the tolerance of the imposed limitations to the reader.
NVIDIA offers a number of technologies/methods for sharing GPUs between multiple workloads, including:
-
NVIDIA Multi-Instance GPU (MIG): On supported GPUs, MIG separates the GPU hardware into up to multiple fully isolated partitions — each with its own memory, cache, and compute cores. This solution prioritizes workload isolation, prevents the sharing of low-level re
-
Time-Slicing GPUs: Typically used by orchestrators such as Kubernetes, time-slicing enables multiple processes to take turns running on the same GPU. Although time-slicing supports renefficient process currently owns the GPU, another process cannot take advantage of the unused compute cores. Additionally, the frequent context switching could also increase under-utilization
-
NVIDIA Virtual GPU (vGPU): Primarily designed for virtualized environments, vGPU serves as a hypervisor software layer exposing a virtual partitioning of the GPU memory and compute cores. This is often implemented using MIG (when HW-supported) or time-slicing.
-
NVIDIA Multi-Process Service (MPS): MPS allows multiple host processes to submit work through a single MPS server process so that kernels from different processes can execute concurrently on available cores. It can reduce context-switching overhead and improve utilization, particularly when individual workloads do not fully saturate the GPU. MPS allows for specifying: 1) limitations on the memory and/or compute cores that each process can use and 2) priority between the different processes. Contrary to MIG, MPS does not guarantee fault isolation and care must be taken to avoid crashing the entire system along with all of the concurrent workloads.
Since our objective is to maximize rehe workloads, we will use MPS. However, we will need to take special precautions to ensure that the workloads do not crash due to their sharing the GPU memory. In particular, this kind of solution is not appropriate for two workloads for which the combined GPU memory requirements exceed the total amount available on the system
We will run two Docker containers, one with our LLM service and one with a simple training job. We will begin by introducing and running each workload independently. Then we will demonstrate how to use MPS to run them concurrently.
For our experiments we will use an Amazon EC2 g6e.12xlarge with 4 NVIDIA L40S GPUs and an AWS Deep Learning (Ubuntu 24.04) AMI. For our LLM we will use Qwen3.8-27B with 27 billion parameters. And for our toy training job we will train a Vision Transformer (ViT)-style image-classification model on a synthetic dataset. Please do not rely on the accuracy or optimality of the instructions and code we will share. Please do not interpret our mention of any tool, framework, library, service, platform, or model as an endorsement of its use. Naturally, the impact of co-locating multiple applications on the same GPU(s) will greatly depend on the details of each workload and the runtime environment; please be sure to run your own extensive evaluation before adopting this type of solution.
Note: In the experiments below, we will use NVMe storage for the Docker images and model weights, since the default storage available (21 GB) is insufficient. While this enables us to run our POC, the drawback to this choice is that NVMe storage is not persistent across an instance restart. A real-world solution would require attaching a dedicated Amazon EBS volume with sufficient storage space.
# Docker setupsudo systemctl stop docker containerdsudo mkdir -p /opt/dlami/nvme/containerd /opt/dlami/nvme/docker /opt/dlami/nvme/docker-tmp /etc/containerd /etc/systemd/system/docker.service.dsudo tee /etc/docker/daemon.json >/dev/null <<'EOF'{"data-root": "/opt/dlami/nvme/docker"}EOFcontainerd config default | sudo tee /etc/containerd/config.toml >/dev/nullsudo sed -i "s|root = '/var/lib/containerd'|root = '/opt/dlami/nvme/containerd'|" /etc/containerd/config.tomlsudo tee /etc/systemd/system/docker.service.d/override.conf >/dev/null <<'EOF'[Service]Environment="DOCKER_TMPDIR=/opt/dlami/nvme/docker-tmp"EOFsudo systemctl daemon-reloadsudo systemctl start containerd docker# Prepare weights directoriessudo mkdir -p /opt/dlami/nvme/weights /opt/dlami/nvme/hfsudo chown -R "$USER":"$USER" /opt/dlami/nvme/weights /opt/dlami/nvme/hfsudo ln -sfn /opt/dlami/nvme/weights /weights# create a directory for experiment scriptsmkdir mps-poc
Deploying an Open-Weight LLM on Amazon EC2
In this section we use the vLLM Docker image to deploy an LLM inference server with the open-weight Qwen3.8-27B model on our g6e.12xlarge Amazon EC2 instance:
sudo docker pull vllm/vllm-openai:v0.34.0
We begin by downloading the model weights from the Hugging Face Qwen repository:
sudo docker run --rm --gpus all --entrypoint hf -v /weights:/weights -e HF_HOME=/weights/hf vllm/vllm-openai:v0.34.0 download Qwen/Qwen3.8-27B --local-dir /weights/Qwen3.8-27B
Next, we prepare a simple measure_latency.py script for measuring the latency of the LLM inference server. The script simulates 2 concurrent users — each sending multiple long-context prompts, and measures the average Time to First Token (TTFT) and latency per request. Note that our choice of token length is somewhat arbitrary; additional testing with varying usage patterns is warranted. However, in the context of our POC, this should give us an indication of the possible impact of our co-location proposal.
import concurrent.futuresimport jsonimport mathimport timeimport urllib.requestURL = "http://127.0.0.1:8000/v1/chat/completions"MODEL = "qwen3.8-27b"PROMPT = ("Analyze GPU scheduling and memory contention. " * 600+ "nSummarize the main trade-offs concisely.")PAYLOAD = {"model": MODEL,"max_tokens": 128,"stream": True,"messages": [{"role": "user", "content": PROMPT}],}def pct(vals: list[float], q: float) -> float:s = sorted(vals)idx = min(len(s) - 1, max(0, math.ceil(q * len(s)) - 1))return s[idx]def one_user(uid: int) -> tuple[int, float, float, int]:req = urllib.request.Request(URL,data=json.dumps(PAYLOAD).encode("utf-8"),headers={"Content-Type": "application/json"},)t0 = time.perf_counter()ttft = Nonechunks = 0with urllib.request.urlopen(req, timeout=300) as resp:for raw in resp:line = raw.decode("utf-8", errors="ignore").strip()if not line.startswith("data: ") or line == "data: [DONE]":continuedelta = json.loads(line[6:])["choices"][0].get("delta", {})if delta.get("content") or delta.get("reasoning_content"):if ttft is None:ttft = time.perf_counter() - t0chunks += 1total = time.perf_counter() - t0return uid, (ttft or total), total, chunksdef main() -> None:one_user(0) # warmupn_requests = 10concurrency = 2t_start = time.perf_counter()with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:futs = [pool.submit(one_user, i) for i in range(n_requests)]results = [f.result() for f in futs]wall = time.perf_counter() - t_startttfts_ms = [r[1] * 1000.0 for r in results]totals_s = [r[2] for r in results]total_chunks = sum(r[3] for r in results)print(f"Summary (n={n_requests}, concurrency={concurrency}, "f"wall={wall:.2f}s):")print(f" TTFT (ms) : mean={sum(ttfts_ms)/len(ttfts_ms):.0f} "f"p95={pct(ttfts_ms, 0.95):.0f} max={max(ttfts_ms):.0f}")print(f" Total (s) : mean={sum(totals_s)/len(totals_s):.2f} "f"p95={pct(totals_s, 0.95):.2f} max={max(totals_s):.2f}")print(f" Throughput : {total_chunks / wall:.1f} chunks/s")if __name__ == "__main__":main()
We start up the LLM server with maximum sequence length of 128K tokens and up to two concurrent users:
sudo docker run -d --name poc-infer --gpus all --ipc=host --network host -v /weights:/weights:ro vllm/vllm-openai:v0.34.0 --model /weights/Qwen3.8-27B --served-model-name qwen3.8-27b --tensor-parallel-size 4 --host 0.0.0.0 --port 8000 --max-model-len 131072 --gpu-memory-utilization 0.90 --max-num-seqs 2
To track the progress (and debug any errors), you can view the output logs by running:
sudo docker logs -f poc-infer
Once the inference application is up and running, we can measure the latency:
sudo docker run --rm --entrypoint python3 --network container:poc-infer -v "$HOME/mps-poc":/poc:ro vllm/vllm-openai:v0.34.0 /poc/measure_latency.py
The resulting runtime performance of the standalone inference server is summarized below:
Summary (n=10, concurrency=2, wall=19.67s):TTFT (ms) : mean=616 p95=820 max=820Total (s) : mean=3.93 p95=3.95 max=3.95Throughput : 65.1 chunks/s
To complete this experiment, run the following cleanup command:
sudo docker stop -t 30 poc-infer && sudo docker rm poc-infer
A Toy Training Workload
Next, we train a toy Vision Transformer (ViT)-style image-classification model. For this experiment, we will use an official PyTorch 2.15 Docker image:
sudo docker pull pytorch/pytorch:2.15.0-cuda13.2-cudnn9-runtime
We create a train-vit.py script in which we define our model and use DistributedDataParallel (DDP) to train it on a synthetic dataset using our four GPUs.
import osimport timeimport torchimport torch.distributed as distimport torch.nn as nnfrom torch.nn.parallel import DistributedDataParallel as DDPfrom torch.utils.data import DataLoader, TensorDatasetclass ToyViT(nn.Module):def __init__(self) -> None:super().__init__()self.proj = nn.Conv2d(3, 768, kernel_size=16, stride=16)enc = nn.TransformerEncoderLayer(d_model=768, nhead=12, dim_feedforward=3072, batch_first=True)self.encoder = nn.TransformerEncoder(enc, num_layers=12)self.head = nn.Linear(768, 10)def forward(self, x: torch.Tensor) -> torch.Tensor:tok = self.proj(x).flatten(2).transpose(1, 2)return self.head(self.encoder(tok).mean(dim=1))def main() -> None:local_rank = int(os.environ["LOCAL_RANK"])world_size = int(os.environ["WORLD_SIZE"])torch.cuda.set_device(local_rank)device = torch.device(f"cuda:{local_rank}")dist.init_process_group("nccl", device_id=device)x = torch.randn(256, 3, 224, 224, dtype=torch.float32)y = torch.arange(256) % 10loader = DataLoader(TensorDataset(x, y), batch_size=32, shuffle=True)model = DDP(ToyViT().to(device), device_ids=[local_rank])opt = torch.optim.AdamW(model.parameters(), lr=1e-4)loss_fn = nn.CrossEntropyLoss()step = 0while True:for bx, by in loader:bx = bx.to(device, non_blocking=True)by = by.to(device, non_blocking=True)t0 = time.perf_counter()opt.zero_grad(set_to_none=True)loss = loss_fn(model(bx), by)loss.backward()opt.step()dt = time.perf_counter() - t0if local_rank == 0:sps = (32 * world_size) / dtprint(f"step={step} step_sec={dt:.4f}"f"samples_per_s={sps:.1f}",flush=True,)step += 1if __name__ == "__main__":main()
To start the training script, we run:
sudo docker run -d --rm --name poc-train --gpus all --ipc=host --network host -v "$HOME/mps-poc":/poc:ro pytorch/pytorch:2.15.0-cuda13.2-cudnn9-runtime torchrun --nproc_per_node=4 --master_port=29511 /poc/train-vit.py
To view the throughput, we run:
sudo docker logs poc-train
The average throughput is 3100 samples/s.
To complete this experiment, we run:
sudo docker stop -t 30 poc-train
In this section we will run the two workloads concurrently using NVIDIA MPS. In order to ensure that we do not hit an out-of-memory (OOM) error, we will limit the GPU memory utilization of the inference workload on each GPU to 32 GB (out of 48 GB) and the training workload to 12 GB. We will also use MPS priority settings to prioritize the latency-sensitive inference workload (priority 0 — normal) over the training workload (priority 1 — below normal).
Step 1: Start MPS
We begin by defining an MPS directory and starting MPS:
# Force all GPU work through MPSsudo nvidia-smi -c EXCLUSIVE_PROCESS# Start MPSexport CUDA_MPS_PIPE_DIRECTORY=/tmp/nvidia-mps-pocexport CUDA_MPS_LOG_DIRECTORY=/var/log/nvidia-mps-pocsudo mkdir -p "$CUDA_MPS_PIPE_DIRECTORY" "$CUDA_MPS_LOG_DIRECTORY"sudo CUDA_MPS_PIPE_DIRECTORY="$CUDA_MPS_PIPE_DIRECTORY" CUDA_MPS_LOG_DIRECTORY="$CUDA_MPS_LOG_DIRECTORY" nvidia-cuda-mps-control -d
Step 2: Run Inference Server
Next, we rerun the inference workload, this time with the 32 GB memory limitation and the MPS configuration:
sudo docker run -d --name poc-infer --gpus all --ipc=host --network host -v /weights:/weights:ro -v /tmp/nvidia-mps-poc:/tmp/nvidia-mps-poc -e CUDA_MPS_PIPE_DIRECTORY=/tmp/nvidia-mps-poc -e CUDA_MPS_CLIENT_PRIORITY=0 vllm/vllm-openai:v0.34.0 --model /weights/Qwen3.8-27B --served-model-name qwen3.8-27b --tensor-parallel-size 4 --host 0.0.0.0 --port 8000 --max-model-len 131072 --gpu-memory-utilization 0.66 --max-num-seqs 2
Once again, we wait until the service is up and running:
sudo docker logs -f poc-infer
Step 3: Run Training Workload
We rerun the training workload with a memory limit of 12 GB and below normal priority:
sudo docker run -d --name poc-train --gpus all --ipc=host --network host -v "$HOME/mps-poc":/poc:ro -v /tmp/nvidia-mps-poc:/tmp/nvidia-mps-poc -e CUDA_MPS_PIPE_DIRECTORY=/tmp/nvidia-mps-poc -e CUDA_MPS_PINNED_DEVICE_MEM_LIMIT=12G -e CUDA_MPS_CLIENT_PRIORITY=1 pytorch/pytorch:2.15.0-cuda13.2-cudnn9-runtime torchrun --nproc_per_node=4 --master_port=29511 /poc/train-vit.py
Step 4: Measure Performance
We assess the impact of the co-location on the LLM latency by rerunning the measure_latency.py script. The new results are captured below:
Summary (n=10, concurrency=2, wall=47.96s):TTFT (ms) : mean=1108 p95=1472 max=1472Total (s) : mean=9.58 p95=9.62 max=9.62Throughput : 26.7 chunks/s
Co-locating the training workload alongside vLLM increased the TTFT by roughly 1.8x and the overall latency by ~2.4x. Recall that our measurement script was purposely defined with a relatively heavy load. In practice, the impact will depend greatly on the LLM usage pattern.
On the other hand, viewing the training logs, we see that training throughput remained 3100 samples/s while the inference server was idle and dropped by only 12.9% (3100 → 2700 samples/s) while the inference server was active.
As mentioned above, whether such slowdowns are acceptable depends on the use cases in question and the user tolerance. A latency-sensitive user may prefer to run two GPU servers (at double the cost) to avoid such compromises.
Note that we could further prioritize the inference workload by limiting the training workload’s access to the GPU cores (e.g., via the CUDA_MPS_ACTIVE_THREAD_PERCENTAGE control). However, this may be undesirable as it will limit the training throughput even when the inference server is idle. Ideally, we would be able to control the training workload dynamically, i.e., automatically reduce the performance of training only while the inference server is engaged. Unfortunately, as of the time of this writing, this does not appear to be a feature supported by MPS (although one could consider a manual implementation).
Step 5: Cleanup
The following commands remove the Docker containers and disable MPS:
sudo docker stop -t 30 poc-train poc-infersudo docker rm poc-inferecho quit | sudo CUDA_MPS_PIPE_DIRECTORY=/tmp/nvidia-mps-poc nvidia-cuda-mps-controlsudo rm -rf /tmp/nvidia-mps-pocsudo nvidia-smi -c DEFAULT
Summary
In the age of agentic AI, running open-weight models on dedicated GPUs can unlock entirely new development workflows. In practice, however, the economics often work against such setups. In this post, we explore the option of co-locating a training workload alongside an inference server using NVIDIA MPS to extract higher utilization from the same GPU server(s).
Naturally, co-location using MPS does not fit every workload. If your inference server expects sustained high utilization or operates under strict latency requirements, this is likely not the right solution for you. But where inference demand is lighter or burstier — and where background training can tolerate modest throughput loss — MPS co-location can tip the balance by maximizing GPU utilization and avoiding the costs of dedicated GPUs.
In this post we have focused on the technical implementation and performance implications of workload co-location. Importantly, a decision to adopt such a solution would also require a full cost analysis that takes into account all aspects of the deployment options that are available.
