NVIDIA Apex
repository·master·Indexed 27 days ago
https://github.com/nvidia/apexA PyTorch utility library for streamlining mixed precision and distributed training. It provides optimized fused kernels, specialized optimizers like FusedAdamSWA, and the ASP (Automatic SParsity) library for 2:4 sparse network generation and pruning. Additional features include the nccl_allocator for accelerated NCCL NVLS collective communications and Triton kernels for Multi-Head Attention and LayerNorm.
What's inside nvidia-apex
- Apex is a PyTorch extension providing NVIDIA-maintained utilities designed to streamline mixed precision and distributed training. It aims to provide up-to-date utilities to users quickly, with some features eventually being integrated into upstream PyTorch.
Use Apex fused optimizers
masterThe
apex.optimizersmodule provides high-performance fused implementations of common optimization algorithms. These fused optimizers are designed to improve training speed by combining multiple operations into a single kernel execution.Available fused optimizers include:
FusedAdamFusedLAMBFusedNovoGradFusedSGD
Install Apex
masterFor detailed installation instructions, including quick-start guides, refer to the official GitHub repository: https://github.com/NVIDIA/apex#quick-start.Requirements for nccl_allocator
masterTo use
nccl_allocator, ensure your environment meets the following strict requirements:- PyTorch: Must include PR #112850.
- NCCL: Version 2.19.4 or newer.
- CUDA Driver: Version 530 or newer (tested on 535) is required for NCCL NVLS.
Install ChannelPermutations (GPU path)
masterTo use CUDA-accelerated search, you must build the permutation search kernels.
Requirements:
- CUDA
- pybind11
- A compatible container like
nvcr.io/nvidia/pytorch:21.12-py3is recommended.
Installation steps: Run the following from the
apex/contrib/sparsity/permutation_testsdirectory to compile the CUDA kernels:pushd ../permutation_search_kernels/CUDA_kernels vcc -O3 -shared -Xcompiler -fPIC -Xcompiler -DTORCH_EXTENSION_NAME=permutation_search_cuda -std=c++11 $(python3 -m pybind11 --includes) permutation_search_kernels.cu -o ../permutation_search_cuda$(python3-config --extension-suffix) popdUse nccl_allocator for faster NCCL NVLS collective communications
masterThe
nccl_allocatormodule enables the use ofncclMemAllocwithin PyTorch to accelerate NCCL NVLS collective communications. It is built uponCUDAPluggableAllocator.To switch between standard
cudaMallocandncclMemAlloc, use thenccl_allocator.nccl_mem(enabled=True)context manager. Whenenabled=True, the allocator usesncclMemAllocfor memory allocations performed within the context block.import os import torch import torch.distributed as dist import apex.contrib.nccl_allocator as nccl_allocator rank = int(os.getenv("RANK")) local_rank = int(os.getenv("LOCAL_RANK")) world_size = int(os.getenv("WORLD_SIZE")) # Initialize the allocator nccl_allocator.init() torch.cuda.set_device(local_rank) dist.init_process_group(backend="nccl") # Use the context manager to enable ncclMemAlloc with nccl_allocator.nccl_mem(): # Allocations inside this block use ncclMemAlloc a = torch.ones(1024 * 1024 * 2, device="cuda") dist.all_reduce(a) torch.cuda.synchronize()Install Apex on Windows (Experimental)
masterWindows support is experimental. A Python-only build is more likely to work. If you use Conda, ensure Apex is installed in the same environment as PyTorch.
Recommended (Python-only):
pip install -v --no-cache-dir .With C++/CUDA extensions (requires PyTorch to be buildable from source on your system):
pip install -v --disable-pip-version-check --no-cache-dir --no-build-isolation --config-settings "--build-option=--cpp_ext" --config-settings "--build-option=--cuda_ext" .Install ChannelPermutations (CPU path)
masterFor CPU-only execution, only NumPy is required. No specialized compilation is necessary.Use ASP for 2:4 sparse network generation
masterIf you need to apply the Channel Permutations technique to generate a 2:4 sparse network for inference, use theASPlibrary located inapex/contrib/sparsity. This library automates the permutation searches for each layer and handles the necessary adjustments to neighboring layers to ensure no extra operations are inserted at runtime.Install Apex from source on Linux
masterTo install Apex from source on Linux, it is recommended to use a nightly PyTorch build and install
Ninjato accelerate compilation. For optimal performance and full functionality, you should build with CUDA and C++ extensions using environment variables.Core Extensions
To build the core
cppandcudaextensions:APEX_CPP_EXT=1 APEX_CUDA_EXT=1 pip install -v --no-build-isolation .Additional Extensions
To include specific additional extensions, set their corresponding environment variables:
APEX_CPP_EXT=1 APEX_CUDA_EXT=1 APEX_FUSED_CONV_BIAS_RELU=1 pip install -v --no-build-isolation .All Contrib Extensions
To build all available
apex.contribextensions at once:APEX_CPP_EXT=1 APEX_CUDA_EXT=1 APEX_ALL_CONTRIB_EXT=1 pip install -v --no-build-isolation .Parallel Building
To reduce build time, you can enable parallel building using
NVCC_APPEND_FLAGSandAPEX_PARALLEL_BUILD:NVCC_APPEND_FLAGS="--threads 4" APEX_PARALLEL_BUILD=8 APEX_CPP_EXT=1 APEX_CUDA_EXT=1 pip install -v --no-build-isolation .Note: If CPU cores or memory are limited, using the
--paralleloption is generally preferred over--threads.Install dependencies for OpenFold triton kernels
masterTo use the
apex.contrib.openfold_tritonsubpackage, you must install theeinopsdependency.pip install einopsUse ASP for sparse training and inference
masterASP (Automatic SParsity) enables sparse training and inference for PyTorch models. To use it, import
ASPfromapex.contrib.sparsityand callASP.prune_trained_model(model, optimizer)before your training loop. This step calculates the sparse mask and applies it to the weights, making the sparse locations fixed for subsequent training or inference.Standard Workflow for Deployment (Inference Mode)
- Load a fully trained (dense) network.
- Prune parameter values in a 2:4 sparse pattern using
ASP.prune_trained_model(model, optimizer). - Fine-tune the pruned model using the same optimizer, learning rate, and hyperparameters used for the original dense model.
- (Optional) Quantize the model.
from apex.contrib.sparsity import ASP # Load your trained model and optimizer model = define_model(..., pretrained=True) optimizer = ... # Augment model and optimizer for sparse training/inference ASP.prune_trained_model(model, optimizer) # Standard training loop to fine-tune the pruned model x, y = DataLoader(args) for epoch in range(epochs): y_pred = model(x) loss = criterion(y_pred, y) loss.backward() optimizer.step() torch.save(model.state_dict(), 'pruned_model.pt')