ptflops

repository·master·Indexed 25 days ago

https://github.com/sovrasov/flops-counter.pytorch

A tool for computing theoretical multiply-add operations (MACs), parameter counts, and per-layer computational costs for PyTorch neural networks. It provides two backends: 'aten' (default), recommended for Transformers and general architectures, and 'pytorch', a legacy mode recommended for CNN analytics. Key functionality is provided via the `get_model_complexity_info` function and the `FlopCounterMode` context manager.

Tokens
2.8K
Snippets
1
Records
17
Agent score
82%

What's inside ptflops

  1. Use the `pytorch` backend for CNN analytics

    master

    The pytorch backend is a legacy mode that considers nn.Modules only. It is recommended for CNNs because it provides better per-layer analytics. Do not use this backend for Transformer architectures.

    Supported Layers:

    • Conv1d/2d/3d (including grouping)
    • ConvTranspose1d/2d/3d (including grouping)
    • BatchNorm1d/2d/3d, GroupNorm, InstanceNorm1d/2d/3d, LayerNorm
    • Activations (ReLU, PReLU, ELU, ReLU6, LeakyReLU, GELU)
    • Linear
    • Upsample
    • Poolings (AvgPool1d/2d/3d, MaxPool1d/2d/3d and adaptive ones)
    • Experimental: RNN, LSTM, GRU, MultiheadAttention, DeformConv2d, and timm vision transformers.

    Usage Tips:

    • If functional-level hooks conflict with custom nn.Module hooks, disable them using backend_specific_config={"count_functional": False}.
    • To handle models with multiple or optional inputs, use the input_constructor argument. This is a function that takes the input spatial resolution as a tuple and returns a dictionary of named input arguments.
    • Use ignore_modules to skip specific layers (e.g., ignore_modules=[torch.nn.Conv2d]).
    • Use verbose=True to see modules that do not contribute to the final complexity count.
  2. Use the `aten` backend for complexity estimation

    master

    The aten backend is the default and is recommended for most architectures, including Transformers, as it considers aten operations. It covers operations like aten.mm, aten.matmul, aten.addmm, aten.bmm, and aten.convolution.

    Usage Tips:

    • Set verbose=True to identify operations that were not considered during computation.
    • Use ignore_modules to exclude specific modules (e.g., ignore_modules=[torch.ops.aten.convolution, torch.ops.aten._convolution]).
    • Note: Per-module statistics are only printed for modules directly nested into the root nn.Module.
  3. Calculate model complexity with `get_model_complexity_info`

    master

    Use get_model_complexity_info to compute the theoretical multiply-add operations (MACs) and the number of parameters in a PyTorch model.

    Arguments:

    • net: The PyTorch model instance.
    • input_size: A tuple representing the input spatial resolution (e.g., (3, 224, 224)).
    • as_strings: If True, returns the results as human-readable strings.
    • backend: Either 'aten' (default) or 'pytorch'.
    • print_per_layer_stat: If True, prints per-layer computational costs.
    • verbose: If True, prints information about uncounted operations/modules.
    import torchvision.models as models
    import torch
    from ptflops import get_model_complexity_info
    
    with torch.cuda.device(0):
      net = models.densenet161()
      macs, params = get_model_complexity_info(net, (3, 224, 224), as_strings=True, backend='pytorch'
                                               print_per_layer_stat=True, verbose=True)
      print('{:<30}  {:<8}'.format('Computational complexity: ', macs))
      print('{:<30}  {:<8}'.format('Number of parameters: ', params))
  4. Convert parameter counts to a readable string with params_to_string()

    master

    Use params_to_string() to convert an integer number of parameters into a human-readable string format.

    If units is not provided, the function automatically selects the most appropriate unit (M for millions or k for thousands). You can explicitly specify units like 'M' (Millions), 'K' (Thousands), or 'B' (Billions) and adjust the decimal precision.

  5. Calculate FLOPs and parameters with get_flops_aten

    master

    The get_flops_aten function provides a high-level interface to estimate the MACs (Multiply-Accumulate operations) and total parameter count of a PyTorch model using the aten backend.

    Arguments:

    • model: The PyTorch model to analyze.
    • input_res: A tuple representing the input resolution (e.g., (3, 224, 224)).
    • print_per_layer_stat: Boolean, defaults to True. If True, prints layer-wise statistics to the output stream.
    • input_constructor: An optional callable that takes input_res and returns a valid input batch (e.g., a tensor or a dictionary of tensors).
    • ost: The output stream for printing (defaults to sys.stdout).
    • verbose: Boolean, defaults to False. Enables warnings for ignored or zero-op operations.
    • ignore_modules: A list of modules to ignore during the counting process.
    • custom_modules_hooks: A dictionary of custom hooks for specific modules.
    • output_precision: Number of decimal places for printed values.
    • flops_units: The unit for FLOPs (e.g., 'GMac', 'MMac').
    • param_units: The unit for parameters (e.g., 'M').
    • extra_config: Additional configuration dictionary.

    Returns: A tuple containing (macs_count, params_sum). If an error occurs during estimation, it returns (None, None).

  6. Calculate FLOPs and parameters using get_flops_pytorch

    master

    The primary entry point for estimating the computational complexity of a PyTorch model. It calculates both FLOPs (Floating Point Operations) and the number of parameters.

    Parameters:

    • model: The PyTorch nn.Module to analyze.
    • input_res: A tuple representing the input resolution (e.g., (3, 224, 224)).
    • print_per_layer_stat (bool): If True, prints a detailed breakdown of FLOPs and parameters per layer.
    • input_constructor (callable, optional): A function that takes input_res and returns a valid input batch (e.g., a dict or torch.Tensor). If None, a tensor of ones is used.
    • ost (file-like, optional): Output stream for printing statistics (defaults to sys.stdout).
    • verbose (bool): If True, prints warnings for unsupported modules treated as zero-ops.
    • ignore_modules (list): A list of module types to ignore during counting.
    • custom_modules_hooks (dict): A mapping of module types to custom FLOPs counting hook functions.
    • output_precision (int): Decimal precision for printed statistics.
    • flops_units (str): Unit for FLOPs (e.g., 'GMac').
    • param_units (str): Unit for parameters (e.g., 'M').
    • extra_config (dict): Configuration dictionary. Use {'count_functional': True} to enable patching of torch.nn.functional and torch.tensor operations.

    Returns:

    • A tuple containing (int(flops_count), params_count). Returns (None, None) if an exception occurs during estimation.
  7. Convert MACs to a readable string with flops_to_string()

    master

    Use flops_to_string() to convert an integer number of MACs (Multiply-Accumulate operations) into a human-readable string format.

    If units is not provided, the function automatically selects the most appropriate unit (GMac, MMac, or KMac) based on the magnitude of the input. You can explicitly specify the unit or adjust the decimal precision.

  8. Compute model complexity with get_model_complexity_info

    master

    Use get_model_complexity_info to analyze a PyTorch model and calculate the number of MACs (Multiply-Accumulate operations) and parameters required for a forward pass.

    Key features:

    • Input Resolution: Provide a tuple for input resolution (e.g., (3, 224, 224)). The batch dimension is added automatically.
    • Backends: Supports FLOPS_BACKEND.PYTORCH (default) and FLOPS_BACKEND.ATEN.
    • Custom Inputs: Use input_constructor if the model requires non-standard inputs (e.g., multiple tensors or dictionaries).
    • Output Formats: Returns a tuple of (macs, params). If as_strings=True, it returns formatted strings (e.g., '1.23 GMac'). If False, it returns raw integers.
    • Layer Statistics: Set print_per_layer_stat=True to print a breakdown of MACs and parameters for each nn.Module layer.