Wandering Giants Compute · Learn
Tutorial

How to Set Up a Multi-GPU Machine Learning Environment

The short answer

Confirm every GPU with nvidia-smi, read the interconnect with nvidia-smi topo -m, install a CUDA build of PyTorch plus Accelerate, DeepSpeed and your training library in a virtual environment, verify NCCL with an all-reduce test, then launch with torchrun or accelerate launch using a DDP, FSDP or DeepSpeed ZeRO config.

GPU checks
nvidia-smi, nvidia-smi topo -m, nvidia-smi nvlink --status
Communication test
nccl-tests all_reduce_perf, or a torch.distributed all-reduce
Launchers
torchrun, accelerate launch, deepspeed
Debug variable
NCCL_DEBUG=INFO
Sharding options
FSDP FULL_SHARD, DeepSpeed ZeRO-2 / ZeRO-3
GPUs per machine on Wandering Giants
1, 2, 4 or 8 of the same card

A multi-GPU machine that is not set up properly fails in expensive ways: jobs that hang at start-up, GPUs sitting at 30% while you pay for 100%, or a sharded checkpoint you cannot load. This tutorial walks through a clean setup on a single machine with 2, 4 or 8 GPUs, with a check at every layer: driver, topology, communication, framework and launch. It finishes with tested DDP, FSDP and DeepSpeed configurations you can reuse. For background on why each piece exists, see the GPU model training guide.

What does a multi-GPU training stack look like?

The stack has five layers, and each one has to work before the next can.

LayerWhat it isHow to check
Hardware and driverGPUs, NVIDIA drivernvidia-smi
InterconnectPCIe, NVLinknvidia-smi topo -m, nvidia-smi nvlink --status
CUDA and NCCLCompute runtime and GPU-to-GPU collectivesnccl-tests, torch.distributed all-reduce
FrameworkPyTorch, Accelerate, DeepSpeed, TRL / Axolotltorch.cuda.device_count(), accelerate env, ds_report
Launcher and strategytorchrun / accelerate / deepspeed; DDP, FSDP, ZeROA 50-step pilot run

Step 1: Launch the machine and check every GPU

On Wandering Giants Compute pick a GPU, choose 2, 4 or 8 cards, choose Root, and launch. The machine comes with Ubuntu, the NVIDIA driver, CUDA and PyTorch, plus SSH and Jupyter. Once in:

bash
nvidia-smi
nvidia-smi --query-gpu=index,name,memory.total,pcie.link.gen.current,pcie.link.width.current --format=csv

You should see every GPU, the same model and memory on each, and no processes already using them. Note the driver version and the "CUDA Version" in the header: that is the newest CUDA runtime the driver supports, and your PyTorch build must not need a newer one.

Next, check how the GPUs are connected:

bash
nvidia-smi topo -m
nvidia-smi nvlink --status    # prints link status if NVLink is present

Read the matrix like this:

CodeMeaningImplication
NV#Connected by # NVLink linksFastest; good for FSDP / ZeRO-3 and tensor parallelism
PIXSame PCIe switchGood peer-to-peer
PXBMultiple PCIe switches, no CPU hopGood
NODEThrough one CPU socket's PCIe rootUsable; slower
SYSAcross CPU socketsSlowest; prefer DDP or ZeRO-2 and larger micro-batches

Interconnect varies between machines, so read this before choosing a sharding strategy. The multi-GPU computing explainer covers the hardware in more depth.

Step 2: Build a clean Python environment

Keep the system PyTorch if it matches your needs, and put everything else in a virtual environment that can see it. The --system-site-packages flag avoids downloading a second multi-gigabyte PyTorch.

bash
python3 -m venv --system-site-packages ~/mgpu && source ~/mgpu/bin/activate
pip install -U pip
python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.device_count())"
pip install -U accelerate "transformers>=4.51" "trl>=0.20" "peft>=0.15" datasets
pip install deepspeed          # compiles some ops on first use; needs the CUDA toolkit
ds_report                      # shows which DeepSpeed ops are compatible
accelerate env

torch.cuda.device_count() must equal the number of GPUs in nvidia-smi. If it does not, check echo $CUDA_VISIBLE_DEVICES.

Step 3: Test GPU-to-GPU communication

Every distributed strategy depends on NCCL, NVIDIA's collective communication library. Test it before you load a model. The quickest test uses PyTorch itself:

python
# allreduce_test.py — torchrun --standalone --nproc_per_node=$(nvidia-smi -L | wc -l) allreduce_test.py
import os, time, torch, torch.distributed as dist

dist.init_process_group("nccl")
rank = int(os.environ["LOCAL_RANK"]); world = dist.get_world_size()
torch.cuda.set_device(rank)

x = torch.ones(256 * 1024 * 1024 // 2, dtype=torch.bfloat16, device="cuda")  # 256 MB
dist.all_reduce(x); torch.cuda.synchronize()            # warm-up
assert x[0].item() == world, "all-reduce returned the wrong value"

iters = 20
t = time.time()
for _ in range(iters):
    dist.all_reduce(x)
torch.cuda.synchronize()
dt = (time.time() - t) / iters
size = x.numel() * x.element_size()
busbw = size * 2 * (world - 1) / world / dt / 1e9
if rank == 0:
    print(f"{world} GPUs, 256 MB all-reduce: {dt*1000:.1f} ms, bus bandwidth ≈ {busbw:.1f} GB/s")
dist.destroy_process_group()
bash
NCCL_DEBUG=INFO torchrun --standalone --nproc_per_node=4 allreduce_test.py 2>&1 | tail -20

The NCCL_DEBUG=INFO output shows which transport NCCL chose: P2P/NVLink, P2P/CUMEM or P2P/IPC for direct peer-to-peer, or SHM when traffic goes through host memory. For a more thorough benchmark, build NVIDIA's nccl-tests:

bash
git clone https://github.com/NVIDIA/nccl-tests.git && cd nccl-tests
make -j CUDA_HOME=/usr/local/cuda
./build/all_reduce_perf -b 8 -e 1G -f 2 -g 4    # -g = GPUs in this machine

Look at the busbw column for the largest message sizes. As a rough guide, PCIe Gen4 peer-to-peer tops out around the low tens of GB/s and PCIe Gen5 roughly doubles that, while NVLink-connected GPUs reach hundreds of GB/s. Do not read too much into one number; what matters is that the test completes, the value is stable, and nothing is unexpectedly slow. If it hangs, try NCCL_P2P_DISABLE=1 to see whether peer-to-peer is the problem, and see the troubleshooting table below.

Step 4: Run a DDP job

Start with plain data parallelism. It is the least likely to go wrong and tells you whether the environment is healthy. Any Hugging Face Trainer or TRL script works unchanged; for example, the QLoRA script from our Llama fine-tuning tutorial, with one change: replace device_map={"": 0} with the local rank so each process loads its copy onto its own GPU.

python
import os
local_rank = int(os.environ.get("LOCAL_RANK", 0))
model = AutoModelForCausalLM.from_pretrained(
    model_id, quantization_config=bnb, torch_dtype=torch.bfloat16,
    device_map={"": local_rank},
)

Then launch on every GPU:

bash
torchrun --standalone --nproc_per_node=4 train_qlora.py
# or
accelerate launch --multi_gpu --num_processes 4 --mixed_precision bf16 train_qlora.py

Each step now processes four micro-batches, so divide gradient_accumulation_steps by four to keep the same effective batch. Watch utilisation while it runs:

bash
nvidia-smi dmon -s um -d 5     # utilisation and memory per GPU every 5 seconds

All GPUs should sit at similar, high utilisation. One GPU busier than the others usually means rank 0 is doing extra work (logging, evaluation) or the data loader is starving the rest.

Step 5: Shard large models with FSDP

When the model does not fit per GPU, shard it. Create an Accelerate config for FSDP. These keys are for Accelerate 1.x; run accelerate config interactively to generate the equivalent for your version.

yaml
# fsdp.yaml
compute_environment: LOCAL_MACHINE
distributed_type: FSDP
mixed_precision: bf16
num_machines: 1
num_processes: 4
machine_rank: 0
fsdp_config:
  fsdp_sharding_strategy: FULL_SHARD
  fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
  fsdp_transformer_layer_cls_to_wrap: LlamaDecoderLayer
  fsdp_backward_prefetch: BACKWARD_PRE
  fsdp_state_dict_type: SHARDED_STATE_DICT
  fsdp_cpu_ram_efficient_loading: true
  fsdp_sync_module_states: true
  fsdp_use_orig_params: true
  fsdp_offload_params: false
bash
accelerate launch --config_file fsdp.yaml train_full.py

Notes on the settings:

  • FULL_SHARD shards weights, gradients and optimiser state (ZeRO-3 equivalent). Use SHARD_GRAD_OP for less communication when memory allows.
  • TRANSFORMER_BASED_WRAP with the decoder layer class makes each transformer block one FSDP unit. Change the class name for other architectures (for example Qwen2DecoderLayer).
  • fsdp_cpu_ram_efficient_loading loads weights on rank 0 only and broadcasts them, which avoids every process loading the full model into CPU RAM at once.
  • SHARDED_STATE_DICT saves fast, per-rank checkpoints. Switch to FULL_STATE_DICT for the final save, or consolidate afterwards, so you can serve the model.
  • With FSDP, remove device_map from from_pretrained; FSDP places the shards.

Step 6: Or shard with DeepSpeed ZeRO

DeepSpeed gives the same sharding with mature CPU and NVMe offload. With the Hugging Face integration, "auto" values are filled from your Trainer arguments.

json
{
  "bf16": {"enabled": "auto"},
  "zero_optimization": {
    "stage": 3,
    "overlap_comm": true,
    "contiguous_gradients": true,
    "reduce_bucket_size": "auto",
    "stage3_prefetch_bucket_size": "auto",
    "stage3_param_persistence_threshold": "auto",
    "stage3_gather_16bit_weights_on_model_save": true,
    "offload_optimizer": {"device": "none"},
    "offload_param": {"device": "none"}
  },
  "gradient_accumulation_steps": "auto",
  "gradient_clipping": "auto",
  "train_batch_size": "auto",
  "train_micro_batch_size_per_gpu": "auto"
}

Point your training arguments at it (deepspeed="ds_zero3.json" in SFTConfig or TrainingArguments) and launch:

bash
accelerate launch --num_processes 4 train_full.py
# or: torchrun --standalone --nproc_per_node=4 train_full.py

Change "stage": 3 to 2 to shard only optimiser state and gradients, which communicates less. Set "offload_optimizer": {"device": "cpu"} to move optimiser state to system RAM when GPU memory is the limit; expect slower steps. Axolotl accepts the same file with deepspeed: ds_zero3.json in its YAML. The trade-offs between strategies are laid out in single vs multi-GPU training.

How do you fix common multi-GPU problems?

Most problems show up in the first minute. This table covers the ones you will meet.

SymptomLikely causeFix
Hangs at init_process_group or first stepNCCL cannot connect; a rank crashedNCCL_DEBUG=INFO; check every rank's log; test with NCCL_P2P_DISABLE=1
CUDA out of memory on rank 0 onlyRank 0 loads extra (evaluation, full model)Use fsdp_cpu_ram_efficient_loading; move eval off rank 0 or shrink eval batch
All ranks OOM with DDPDDP does not save memorySwitch to FSDP / ZeRO-3, or QLoRA
Low GPU utilisation on all cardsData loader too slowRaise dataloader_num_workers; pre-tokenise; use packing
Training slower on 4 GPUs than expectedSmall batch, slow interconnect, ZeRO-3 on PCIeLarger micro-batch; try ZeRO-2 or SHARD_GRAD_OP
NCCL timeout mid-runOne rank stalled (disk, eval, OOM)Find the slow rank in logs; raise timeout only after fixing cause
Checkpoint will not load on one GPUSharded formatSave FULL_STATE_DICT at the end, or use DeepSpeed's zero_to_fp32.py
bitsandbytes error with FSDPQLoRA + FSDP needs specific settingsUse DDP for QLoRA, or follow current PEFT/bitsandbytes FSDP-QLoRA docs

What does a multi-GPU machine cost per hour?

A machine of N cards costs N × the per-GPU price, billed by the minute. So test cheaply: run your environment checks and a 50-step pilot on the full machine, which takes minutes, before committing to hours.

MachinePrice per GPU-hourPer hour for the machine15-minute setup and pilot
4 × L40S$1.89/hr$7.56$1.89
4 × A100 80GB$3.79/hr$15.16$3.79
8 × H100$4.99/hr$39.92$9.98
8 × B200$15.49/hr$123.92$30.98

Prices as of November 2026. The cheapest habit in multi-GPU work is preparing data, scripts and configs on a single cheap card (or your laptop), then launching the big machine only to run.

When renting from Wandering Giants fits

Wandering Giants Compute gives you exactly the environment this tutorial assumes: one machine with 1, 2, 4 or 8 of the same GPU, root access, Ubuntu, CUDA and PyTorch installed, billed per minute and stopped automatically if your prepaid credit runs out. You can pause a machine and keep its disk, with your environment and checkpoints, for about 3¢ an hour per 50 GB.

It is not a multi-node cluster: there is no InfiniBand fabric between machines and no managed Kubernetes or Slurm. If your training needs more than eight GPUs working on one job, use a provider that offers multi-node clusters, such as Lambda, CoreWeave or Nebius. To compare where else to rent multi-card machines, see multi-GPU cloud servers.

Frequently asked questions

How do I check that PyTorch sees all my GPUs?

Run python -c "import torch; print(torch.cuda.device_count())". It should print the number of GPUs nvidia-smi lists. If it prints fewer, check CUDA_VISIBLE_DEVICES and that PyTorch was installed with a CUDA build matching the driver.

How do I test NCCL between GPUs?

Build NVIDIA's nccl-tests and run all_reduce_perf -b 8 -e 1G -f 2 -g <number of GPUs>, or run a short torch.distributed all-reduce script with torchrun. Look at the bus bandwidth at large message sizes and confirm there are no errors or hangs.

What does nvidia-smi topo -m tell me?

It prints a matrix of how each pair of GPUs is connected: NV# for NVLink, PIX or PXB for a shared PCIe switch, NODE for the same CPU socket, and SYS for paths across sockets. Faster links make sharded training and tensor parallelism more efficient.

Why does my multi-GPU training hang at start-up?

Usually NCCL cannot set up its connections, one process crashed before joining, or ranks disagree on the number of processes. Run with NCCL_DEBUG=INFO, check every rank's log, and confirm the launch uses the same world size everywhere. Peer-to-peer problems can be isolated with NCCL_P2P_DISABLE=1 as a test.

Should I use accelerate or torchrun?

Both start one process per GPU. torchrun is part of PyTorch and needs nothing else; accelerate launch adds config files for FSDP, DeepSpeed and mixed precision, which suits Hugging Face code. They are interchangeable for Trainer and TRL scripts.

Can I run one experiment per GPU instead of one job across all of them?

Yes. Set CUDA_VISIBLE_DEVICES=0 for the first run, =1 for the second and so on. For hyperparameter sweeps on small models this often beats one distributed job, because there is no communication at all.

Wandering Giants Compute

Rent the GPU for this, by the minute.

Launch a 2, 4 or 8-GPU machine with Ubuntu, CUDA and PyTorch ready, and have a distributed job running in minutes.

Prepaid credit, billed by the minute, stops itself when credit runs out. Prices in £, $, €, ¥, CA$, A$, CHF and S$; UK prices include VAT.

Keep reading

About this article. Written by the Wandering Giants Compute team, the people who run Wandering Giants Compute. Hardware figures are the manufacturers’ published specifications. Speeds and costs marked as estimates are worked out from those specifications and our current prices, with the method shown; they are not measured benchmarks. Wandering Giants prices are taken live from our price list each time this page is built.

Last reviewed 25 November 2026.