Hugging Face Accelerate Explained: Multi-GPU Training and Inference Made Practical

How accelerate huggingface works: accelerate config and launch, DeepSpeed and FSDP choices, Trainer, and what multi-GPU inference costs in latency.

Hugging Face Accelerate Explained: Multi-GPU Training and Inference Made Practical
Written by TechnoLynx Published on 11 Jul 2026

Hugging Face Accelerate, the library people look up as accelerate huggingface, runs the same PyTorch code across distributed configurations. You keep your own PyTorch training loop. The Accelerator class and its prepare() method wrap the model, optimizer, scheduler and dataloader for whatever setup the script finds, so the same script runs on one GPU or many. A saved config file plus the accelerate launch command take care of starting the processes, and switching the backend to DeepSpeed or FSDP is mostly a config change, not a rewrite. It removes the plumbing you would otherwise write by hand.

What Accelerate Does That Hand-Written DDP Makes You Do Yourself

Plain PyTorch DistributedDataParallel (DDP) requires you to spawn several processes and build one DDP instance in each, and DDP then synchronises gradients through autograd hooks that fire during the backward pass. For basic cases that only takes a few extra lines to set up the process group. Each distributed training framework has its own way of doing things, which means custom code to adapt it to your training loop and environment.

With Accelerate, that adaptation code shrinks to a few calls:

  • prepare() puts the model in the right container for the setup, swaps the optimizer and scheduler for AcceleratedOptimizer and AcceleratedScheduler, and returns a dataloader that is sharded across processes.
  • accelerator.backward(loss) replaces loss.backward(), scales gradients for mixed precision and calls the right backward for the backend, for example DeepSpeed.
  • unwrap_model() strips the distributed wrapper before you save. Skip it and the saved state dict includes any extra layers the wrapper added, and the weights will not load back into the base model.
  • save_state() and load_state() checkpoint the model, optimizer, random generators and schedulers so a run can resume.

Hugging Face describes this as running the same PyTorch code across any distributed configuration by adding four lines. Underneath, Accelerate still calls torch.distributed (or torch_xla on TPUs). That is worth stating plainly. Accelerate places the model on devices and manages processes across them. It does not change the kernels doing the maths: those are still the same CUDA kernels reached through cuBLAS, cuDNN or fused attention paths.

How Do I Start a Multi-GPU Run with Accelerate Config and Accelerate Launch?

The order is config first, launch second: accelerate config asks a series of questions about your system and saves the answers as a default config file. The CLI reference says to always run it first on your machine. Skip it and Accelerate falls back to very basic defaults based on what it detects about your system. The answers go into default_config.yaml in Accelerate’s cache folder, and accelerate launch reads that file to set up the run.

# one-time, per machine
accelerate config

# uses the saved default_config.yaml
accelerate launch train.py --your_script_args

# explicit flags: two GPUs, fp16 mixed precision, no warnings
accelerate launch --multi_gpu --mixed_precision=fp16 --num_processes=2 train.py

# a second saved configuration, e.g. an FSDP setup
accelerate launch --config_file fsdp_config.yaml train.py

The --multi_gpu flag asks for a distributed GPU launch, and --num_processes sets the number of GPUs to use. To keep several setups side by side, for example plain DDP and FSDP, save each as its own YAML file and pass it with --config_file. --use_deepspeed, --use_fsdp and --use_megatron_lm pick the backend from the command line. Mixed precision can be FP16 or BF16, and the CLI reference states that BF16 needs Nvidia Ampere GPUs and PyTorch 1.10 or later.

accelerate launch wraps the platform-specific launch commands so you do not have to remember each one. If you want the details of what the launcher sets up (process spawning, rank and world-size variables, process group initialisation), our walkthrough of how accelerate launch works covers them. Config choices for particular workloads are covered in the guides on accelerate config for simulation and compute workloads and accelerate config for CV training.

Going Multi-Node

According to the Accelerate docs, a multi-node run works like a torchrun run. Put the code and data on every node, or on a shared filesystem. Install the same packages on every node. Run accelerate config on the main node, giving it the number of nodes, the main node’s IP address and port, and rank 0 for that node. Copy the file to the workers and change machine_rank to 1, 2, 3 and so on. Then run accelerate launch on every node, not only the main one, because training will not start otherwise.

Why Your Multi-GPU Loss Curve Will Not Match the Single-GPU Run

The batch size you give the dataloader is a per-GPU batch size. The Accelerate docs give the example that a batch size of 64 on two GPUs is really a batch of 128. Accelerate also steps the learning-rate scheduler once per process, so on two GPUs the scheduler moves twice as fast as on one, unless you changed the single-GPU batch size to match. The same guide recommends scaling the learning rate linearly with the number of devices.

Gradient accumulation and mixed precision also bring some expected degradation of their own. Batch-wise loss can look worse than on a single device, while overall loss and final metrics should end up roughly the same. The Transformers documentation gives the effective batch size as per-device batch size × number of devices × gradient accumulation steps.

So a run that “behaves differently on four GPUs” is also running a different global batch and a different schedule. We would check that arithmetic before suspecting the hardware or the library.

Accelerate with DeepSpeed and FSDP: When the Model Stops Fitting

Plain data parallelism copies the model, gradients and optimizer states to every GPU and splits the batches between them. That raises throughput, but only if the whole model fits on one device. When it does not fit, sharding addresses the problem. FSDP spreads weights, gradients and optimizer states across GPUs and gathers each layer’s weights just before that layer computes. It saves memory at the cost of extra communication. DeepSpeed’s ZeRO stages shard optimizer states (stage 1), then gradients as well (stage 2), then parameters as well (stage 3), and can offload to CPU or NVMe on top of that. FSDP full sharding maps to DeepSpeed ZeRO stage 3.

In Hugging Face’s FSDP post, DDP could not train GPT-2 1.5B on two GPUs even at batch size 1 and hit CUDA out-of-memory. FSDP with ZeRO stage 3 ran at batch size 5 per GPU, and adding CPU offload raised that to 14 per GPU. When the model does fit, though, DDP with mixed precision was the fastest option in the same tests.

Situation Backend What to watch
Model, gradients and optimizer fit on one GPU DDP Fastest train time in Hugging Face’s FSDP tests
Model does not fit; you want PyTorch-native sharding FSDP Needs a wrap policy, e.g. fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP; offload is all-or-nothing
Model does not fit; you need finer offload control or NVMe DeepSpeed ZeRO-3 Can offload parameters and optimizer separately, including to NVMe
Few GPUs and tight memory Watch DeepSpeed upcasting DeepSpeed keeps fp32 master weights, which can roughly double memory on small GPU counts

Hugging Face compared FSDP full sharding with DeepSpeed ZeRO-3 on IBM Granite 7B across four A100 GPUs and found they perform similarly. Precision handling is where they differ. DeepSpeed always keeps fp32 master weights. On many GPUs the cost of that upcasting is negligible, but on a small number of GPUs the 2x memory increase can be significant. Without mixed precision, FSDP can run the optimizer in low precision. With mixed precision, both backends upcast while preparing the model, and FSDP then saves checkpoints in the upcast precision. Hugging Face found this difference when the same Mistral-7B run converged under DeepSpeed and failed to converge under FSDP. Accelerate 0.30.0 added automatic upcasting for FSDP in mixed-precision mode.

There are two ways to use DeepSpeed through Accelerate. You can point accelerate config at a DeepSpeed config file, which gives you all the core features. Or you can use the deepspeed_plugin with default options, which supports a subset of features and needs no code changes. With a DeepSpeed config file, Accelerate ignores its own settings for gradient accumulation, clipping, ZeRO stage, offload and mixed precision, and they have to be set in the DeepSpeed file instead. Saving also changes under ZeRO-3: the state dict holds only placeholders. To get loadable weights, you gather the full 16-bit weights onto one GPU at save time, which is slow and memory-hungry.

Gradient checkpointing trades compute for memory when memory is short. Hugging Face’s ND-Parallel guide and Trainer docs put its cost at roughly 20% to 30% more training time, in return for much lower activation memory.

Combining Strategies with ParallelismConfig

For larger jobs, Accelerate’s ParallelismConfig lets you set degrees for FSDP sharding (dp_shard_size), replication (dp_replicate_size), context parallelism (cp_size) and tensor parallelism (tp_size) together, and setting any degree to 1 turns that strategy off. Hugging Face usually tries to avoid running FSDP across more than one full node because the communication overhead grows too high. Hybrid sharding (HSDP) handles this by sharding within a node and replicating across nodes, and you enable it by setting both dp_shard_size and dp_replicate_size. Tensor parallelism is only effective inside a single node, because it has to sync activations between devices during every forward pass.

Where the Trainer Class Fits

The Hugging Face Trainer sits on top of Accelerate, not beside it. Trainer calls the Accelerate APIs and leaves all the distributed mechanics to Accelerate. In practice you run accelerate config and then accelerate launch on a Trainer-based script, and Accelerate reads the same default_config.yaml to set up training. Trainer computes the global batch as per-device batch size times number of devices.

Trainer is the convenient choice when its loop fits your task, and a custom Accelerate loop is the better choice when you need control over every step.

Can Accelerate Split One Large Model Across GPUs for Inference, and What Does It Cost?

Yes, but only one GPU works at a time. Big Model Inference creates an empty model skeleton on PyTorch’s meta device, then loads checkpoint shards one at a time and places each layer according to device_map. With device_map="auto", layers fill the GPUs first, then CPU RAM, then disk as memory-mapped tensors. The Accelerate docs say plainly that this model parallelism is naive: only one GPU works at any moment while the others sit idle. Offloaded weights are not prefetched, so they move to the GPU only when they are needed, and disk offload can be very slow without fast storage such as NVMe.

Hugging Face’s BLOOM inference write-up gives a concrete comparison. Users reported running BLOOM unchanged on 2 A100s at 15 seconds per token, against 10 milliseconds per token on 8 80GB A100s. DeepSpeed-Inference was faster because it uses tensor parallelism and custom CUDA kernels. The same post notes that the tensor-parallel route may need developer time for models it has not been tried on, while Accelerate’s naive approach should work out of the box with any model.

Strategy What it splits Latency for one prompt Best when
Full copy per GPU (DDP-style, split_between_processes) Prompts Unchanged The model fits and you have many prompts
device_map Layers across devices Slightly worse The model does not fit and the interconnect is slow
Pipeline parallelism (prepare_pippy) Layers, with several inputs in flight Faster than naive splitting Several inputs can keep every stage busy
Tensor parallelism Weight matrices Lower One component’s weights do not fit and the interconnect is fast

Interconnect decides between device_map and tensor parallelism. Tensor parallelism communicates at every block boundary. That needs NVLink-class bandwidth: over PCIe the per-layer traffic can outweigh the compute it saves, and device_map becomes the better choice. DeepSpeed ZeRO-3 is a further route for inference, because it can load models that no single GPU could hold and uses only stage 3, with no optimizer or scheduler.

For sizing, accelerate estimate-memory estimates the VRAM a Hub model needs, and the docs suggest adding up to 20% on top for inference. Also allow for the CUDA kernels PyTorch loads on its first allocation, which take about 1-2GB depending on the GPU, before you set max_memory.

Why Does Accelerate Use Only One GPU When the Machine Has Several?

Work through these checks in order:

  1. Was the script started with accelerate launch? Running python train.py starts one process, and Accelerate then runs it as a single-device job.
  2. Does a config file exist? Without one, Accelerate uses basic defaults. Run accelerate config and answer the multi-GPU questions, or pass --multi_gpu --num_processes=N explicitly.
  3. Is the right config being read? If you keep several YAML files, check which one --config_file points to, because otherwise the cached default_config.yaml is used.
  4. In a notebook, did you set num_processes? notebook_launcher() takes the process count as an argument, and any CUDA code, including CUDA imports, has to live inside the function you pass to it.

When Adding GPUs Makes the Run Slower

Every distributed setup adds synchronisation: DDP syncs at construction, forward and backward, and a slow process holds back every other one. FSDP adds a gather before each layer and a reduce-scatter after the backward pass. With a small per-GPU batch, it is our judgement that this fixed communication cost can outweigh the extra compute. That gets worse over PCIe, where Hugging Face’s docs prefer device_map to tensor parallelism. Old code that still uses nn.DataParallel has its own documented problem: it is usually slower than DDP even on one machine. On the inference side, a device_map split runs only one GPU at a time.

To diagnose a run like this, we would compare throughput in samples per second at the same global batch, not loss curves, and then profile where each step’s time goes on the target hardware, the work TechnoLynx’s GPU performance engineering covers. Accelerate makes switching the parallelism strategy cheap. Which strategy your hardware rewards is a separate question. You only find that out by measuring on the hardware you have.