Hugging Face Accelerate

repository·main·Indexed 27 days ago

https://github.com/huggingface/accelerate

A lightweight library that allows PyTorch users to run training scripts on any device configuration—including single/multi-GPU, TPU, multi-CPU, and DeepSpeed—without rewriting training loops. It abstracts boilerplate for distributed training and mixed precision (fp16, bf16, fp8) while providing utilities like regional compilation via `accelerate.utils.compile_regions()` and official Docker images for various hardware accelerators.

Tokens
66.1K
Snippets
154
Records
339
Agent score
93%

What's inside Accelerate

  1. Understand Accelerate's initialization and state management

    main
    Accelerate manages distributed environments using AcceleratorState. This state is initialized the first time you instantiate an Accelerator (or its barebones version PartialState). It analyzes the launch environment to determine the distributed setup, the number of processes, and the current process ID. This state is uniquely shared across all instances of AcceleratorState within the same run.
  2. Understand Stateful Classes in Accelerate

    main
    Accelerate uses several stateful classes that follow a singleton pattern. This means all instances of a specific class share the same state, which is initialized upon the first instantiation. These classes are immutable and are used to store information about specific configurations or states within your distributed training environment.
  3. Caveats for Megatron-LM Integration

    main

    When using the Megatron-LM integration with 🤗 Accelerate, be aware of the following technical constraints and behaviors:

    • Supported Architectures: Supports Transformers GPT2, Megatron-BERT, and T5 models (Decoder-only, Encoder-only, and Encoder-Decoder).
    • Model Forward Pass: The model(**batch_data) call returns only the loss(es) averaged across data parallel ranks. For GPT models, logits are also returned, but they are not gathered across data parallel ranks automatically. To compute performance metrics, use accelerator.utils.gather_across_data_parallel_groups to gather logits.
    • Main Process Identification: The main process is the last rank (due to pipeline/tensor/data parallelism interplay). Consequently, accelerator.is_main_process and accelerator.is_local_main_process will return True for the last rank.
    • Model Initialization: Calling accelerator.prepare creates a Megatron-LM model with random weights corresponding to the Transformers model. You must use accelerator.load_state to load actual Megatron-LM checkpoints with matching TP (Tensor Parallel), PP (Pipeline Parallel), and DP (Data Parallel) partitions.
    • Gradient Accumulation: gradient_accumulation_steps must be set to 1. In Megatron-LM pipeline parallelism, micro-batches are synonymous with gradient accumulation.
    • Checkpointing: Always use accelerator.save_state and accelerator.load_state for saving and loading checkpoints.
    • Checkpoint Reshaping: Currently, checkpoint reshaping and interoperability support is only available for GPT models.
  4. Understand TPU training latency and memory allocation

    main

    When starting training on a TPU, you may experience initial slowness. This occurs because the TPU runs through several batches to determine optimal memory allocation.

    Note on Batch Sizes: If your evaluation code uses a larger batch size than your training code, the TPU may trigger a memory reallocation process. To avoid performance hits during evaluation, consider keeping the evaluation batch size identical to the training batch size.

  5. Prepare a training script for SageMaker

    main

    When running on SageMaker, you must save your model artifacts to a specific directory so they can be uploaded to S3 after training. Use either /opt/ml/model or the environment variable os.environ["SM_MODEL_DIR"] as your save directory.

    Important Note on Hyperparameters: SageMaker does not support argparse actions. If you use boolean hyperparameters, you must specify the type as bool in your script and provide an explicit True or False value.

  6. Enable Big Model Inference in Hugging Face Transformers

    main

    If you are using the Hugging Face transformers library, you can leverage Accelerate's Big Model Inference directly within the from_pretrained constructor.

    To enable it, pass device_map="auto". You can also pass torch_dtype (e.g., torch.float16) to reduce memory usage by loading the model in lower precision.

    from transformers import AutoModelForSeq2SeqLM
    import torch
    
    # Basic Big Model Inference
    model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0pp", device_map="auto")
    
    # Big Model Inference with lower precision to save more memory
    model = AutoModelForSeq2SeqLM.from_pretrained(
        "bigscience/T0pp", 
        device_map="auto", 
        torch_dtype=torch.float16
    )
  7. Configure MS-AMP (Deprecated) for FP8

    main

    ⚠️ Warning: MS-AMP is unmaintained and not recommended for new projects. It has compatibility issues with CUDA 12.x+ and PyTorch 2.2+.

    If using for legacy purposes, you can set the optimization_level via FP8RecipeKwargs:

    • O1: Casts weight gradients and all_reduce communications to 8-bit.
    • O2: Also casts first-order optimizer states to 8-bit (supports Adam only).

    Configuration can be done via accelerate launch --fp8_backend=msamp --fp8_opt_level=O2 or in config.yaml.

    from accelerate import Accelerator
    from accelerate.utils import FP8RecipeKwargs
    
    kwargs = [FP8RecipeKwargs(backend="msamp", optimization_level="O2")]
    accelerator = Accelerator(mixed_precision="fp8", kwarg_handlers=kwargs)
  8. Fine-tune a quantized model

    main

    Pure 8-bit or 4-bit training is not possible. To fine-tune quantized models, use Parameter Efficient Fine-Tuning (PEFT) methods (like training adapters via the peft library).

    Important: When loading a model for training, do not pass a device_map. Accelerate will automatically load the model onto your GPU. Use device_map="auto" for inference only.

  9. Understand the limitations of standard PyTorch model loading for large models

    main

    The standard PyTorch workflow for loading models involves three steps:

    1. Creating the model with randomly initialized weights.
    2. Loading the weights (state dict) from disk into RAM.
    3. Loading those weights into the model instance.

    For large models, this approach is memory-inefficient because it requires holding multiple copies of the model in RAM simultaneously (one for the initialized model and one for the loaded state dict), which can lead to Out-of-Memory (OOM) errors during the loading process.

  10. Explore Official Accelerate Basic Examples

    main

    Accelerate provides barebones examples for common tasks to help you get started with distributed training. These include:

    • NLP: Barebones NLP example and a distributed version for Jupyter Notebooks.
    • Computer Vision: Barebones computer vision example and a distributed version for Jupyter Notebooks.
    • Kaggle: Instructions for using Accelerate in Kaggle environments.
  11. Configure and launch distributed training with Accelerate CLI

    main

    Accelerate provides a unified command line interface to launch training scripts across different distributed setups (DeepSpeed, FSDP, etc.).

    1. Configure your environment: Run accelerate config to interactively set up your training environment. This creates a default_config.yaml in the Accelerate cache.
    2. Test your setup: Run accelerate test to launch a short script that verifies your distributed environment is working correctly.
    3. Launch your script: Use accelerate launch to run your training script.

    Tip: If your configuration file is in a non-default location, use the --config_file flag with accelerate launch or accelerate test.