NVIDIA Apex

repository·master·Indexed 27 days ago

https://github.com/nvidia/apex

A 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.

Tokens
5.3K
Snippets
14
Records
27
Agent score
94%

What's inside nvidia-apex

  1. Overview of Apex (A PyTorch Extension)

    master
    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.
  2. Use Apex fused optimizers

    master

    The apex.optimizers module 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:

    • FusedAdam
    • FusedLAMB
    • FusedNovoGrad
    • FusedSGD
  3. Install ChannelPermutations (GPU path)

    master

    To use CUDA-accelerated search, you must build the permutation search kernels.

    Requirements:

    • CUDA
    • pybind11
    • A compatible container like nvcr.io/nvidia/pytorch:21.12-py3 is recommended.

    Installation steps: Run the following from the apex/contrib/sparsity/permutation_tests directory 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)
    popd
  4. Use nccl_allocator for faster NCCL NVLS collective communications

    master

    The nccl_allocator module enables the use of ncclMemAlloc within PyTorch to accelerate NCCL NVLS collective communications. It is built upon CUDAPluggableAllocator.

    To switch between standard cudaMalloc and ncclMemAlloc, use the nccl_allocator.nccl_mem(enabled=True) context manager. When enabled=True, the allocator uses ncclMemAlloc for 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()
  5. Install Apex on Windows (Experimental)

    master

    Windows 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" .
  6. Use ASP for 2:4 sparse network generation

    master
    If you need to apply the Channel Permutations technique to generate a 2:4 sparse network for inference, use the ASP library located in apex/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.
  7. Install Apex from source on Linux

    master

    To install Apex from source on Linux, it is recommended to use a nightly PyTorch build and install Ninja to 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 cpp and cuda extensions:

    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.contrib extensions 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_FLAGS and APEX_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 --parallel option is generally preferred over --threads.

  8. Use ASP for sparse training and inference

    master

    ASP (Automatic SParsity) enables sparse training and inference for PyTorch models. To use it, import ASP from apex.contrib.sparsity and call ASP.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)

    1. Load a fully trained (dense) network.
    2. Prune parameter values in a 2:4 sparse pattern using ASP.prune_trained_model(model, optimizer).
    3. Fine-tune the pruned model using the same optimizer, learning rate, and hyperparameters used for the original dense model.
    4. (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')