TorchANI

repository·main·Indexed 19 days ago

https://github.com/aiqm/torchani

An open-source PyTorch implementation of the ANI neural network potential family for training, developing, and researching interatomic potentials. TorchANI 2.0 includes C++ and CUDA extensions such as CUAEV for accelerated AEV calculation and MNP (Multi Net Parallel) for optimized inference. It provides utilities for single-point calculations, access to legacy state dicts, and a command-line interface via the `ani` executable.

Tokens
25.3K
Snippets
86
Records
124
Agent score
68%

What's inside torchani

  1. Overview of TorchANI

    main

    TorchANI is an open-source library designed for the training, development, and research of ANI-style neural network interatomic potentials. It is maintained by the Roitberg group and is built to work with torch (PyTorch).

    Note for legacy users: If you are upgrading from a version prior to 2.0, your code may require updates to remain compatible with new features. You should consult the migration guide provided in the documentation.

  2. Use updated class names and signatures for AEV and ANI components

    main

    Several core classes have been renamed or have updated method signatures in TorchANI 2:

    1. torchani.nn.ANIModel has been renamed to torchani.nn.ANINetworks. While the old name is temporarily supported, it is slated for removal.
    2. torchani.AEVComputer initialization has changed. If you need the old signature, use the torchani.aev.AEVComputer.from_constants constructor.
    3. Component Workflow: The interaction between SpeciesConverter, AEVComputer, and ANINetworks has been streamlined. SpeciesConverter now typically takes atomic_nums directly, and AEVComputer no longer requires the same tuple-based input as before.

    Separating Neighborlists: You can now separate the AEVComputer and torchani.neighbors.Neighborlist parts of a calculation. This is useful if you want to reuse a computed neighborlist in other modules (like pair potentials).

    import torchani
    
    # New workflow for components
    converter = torchani.nn.SpeciesConverter("...")
    aevc = torchani.AEVComputer("...")
    ani_nets = torchani.ANINetworks("...")
    ensemble = torchani.Ensemble("...")
    
    idxs = converter(atomic_nums)
    aevs = aevc(idxs, coords, cell, pbc)
    energies = ani_nets(idxs, aevs)
    
    # Separating Neighborlist
    neighborlist = torchani.neighbors.AllPairs()
    # ... setup aevc and converter ...
    cutoff = aevc.radial.cutoff
    neighbors = neighborlist(cutoff, idxs, coords, cell, pbc)
    aevc = aevc.compute_from_neighbors(idxs, neighbors)
  3. Access constants and parameter files via torchani.constants

    main

    TorchANI packages necessary constants and parameter files (stored in HDF5 or JSON formats) directly within the library to compute various potentials.

    Important: Do not attempt to access or modify the raw data files in the resources directory directly, as the storage format is considered an internal implementation detail. Instead, always use the torchani.constants module to access this data. If you use these constants in research, ensure you cite the corresponding scientific articles.

  4. GPU Support and Compatibility

    main

    TorchANI 2.0 is highly recommended to be run on CUDA-enabled GPUs for performance.

    • CUDA: Supported and recommended.
    • AMD (ROCm/HIP): Untested.
    • macOS: No CUDA support; performance on Apple Metal Performance Shaders (MPS) is untested.
  5. Access legacy ANI model state dicts

    main

    If you are migrating from a previous version of TorchANI and require the old state dicts of ANI models, use the .legacy_state_dict() method instead of the standard .state_dict() method.

    # Example usage (conceptual)
    model.legacy_state_dict()
  6. Getting started with TorchANI

    main

    To begin using TorchANI, you can follow these primary paths:

    1. Installation: Install the library via conda or pip. For building from source, refer to the README in the GitHub repository.
    2. User Guide: Learn how to use TorchANI models in research or applications, understand the main classes, and learn how to extend them.
    3. API Reference: For a detailed description of all public functions, classes, methods, and properties. This assumes a basic understanding of Python and torch.
    4. Publications: Consult this section for articles regarding TorchANI and its specific models. You should cite the corresponding articles if you use TorchANI in scientific publications.
  7. Install TorchANI from source (GitHub)

    main

    To build and install directly from the GitHub repository:

    1. Clone the repository and enter the directory.
    2. Create a conda or mamba environment using the provided environment.yaml.
    3. Install the package in editable mode using pip install --no-deps -v -e ..
    4. Build the extensions using ani build-extensions.

    If using a Python venv instead of conda, install the development requirements first using pip install -r dev_requirements.txt.

    # Clone and enter
    git clone https://github.com/aiqm/torchani.git
    cd ./torchani
    
    # Create environment
    conda env create -f ./environment.yaml
    
    # Install package
    pip install --no-deps -v -e .
    
    # Build extensions
    ani build-extensions
  8. Perform single-point calculations with single_point()

    main

    Instead of calling models directly with a tuple of (species_indices, coords), it is recommended to use the torchani.single_point utility. This approach is more robust as it allows models to return multiple quantities (like charges, forces, or hessians) in a dictionary format and handles gradient requirements automatically.

    To obtain forces and hessians, pass forces=True and hessians=True to the function.

    import torchani
    from torchani import single_point
    
    # Setup
    atomic_nums = torch.tensor([[1, 6, 6, 1]])
    coords = torch.tensor(...) # your coordinates
    model = torchani.models.ANI1x()
    
    # Standard usage
    result = single_point(model, atomic_nums, coords)
    energies = result["energies"]
    
    # Advanced usage (forces and hessians)
    result = single_point(model, atomic_nums, coords, forces=True, hessians=True)
    atomic_charges = result["atomic_charges"]  # Only for models that support this
    energies = result["energies"]
    forces = result["forces"]
    hessians = result["hessians"]
  9. Install Torchani CSRC extensions from source

    main

    The CSRC (Cpp source files) provides two main extensions:

    • CUAEV: CUDA Extension for AEV calculation. Provides ~3X speedup for AEV computation and ~2.6X for energy+force training.
    • MNP: Multi Net Parallel using OpenMP (Inference Only) to reduce CUDA call overhead.

    To install, ensure gcc and cuda are configured. Run the following from the torchani directory:

    Standard Installation:

    • Build only for detected GPUs: python setup.py install --ext
    • Build for all GPUs (recommended for HPC/clusters): python setup.py install --ext-all-sms

    Development Installation: Note: pip install -e . is required for the very first install due to a known pip issue.

    • Build only for detected GPUs: pip install -e . && pip install -v -e . --global-option="--ext"
    • Build for all GPUs: pip install -e . && pip install -v -e . --global-option="--ext-all-sms"
    python setup.py install --ext-all-sms
  10. Create models for training using torchani.arch

    main

    The use of torchani.nn.Sequential is highly discouraged due to being error-prone and verbose. Instead, use factory functions in torchani.arch or the torchani.arch.Assembler class to build models ready for training.

    Option 1: Simple Factory Functions

    Use torchani.arch.simple_ani for a quick setup with random weights.

    Option 2: Using Assembler for Customization

    Use torchani.arch.Assembler to fine-tune components like radial/angular terms, strategies (e.g., cuAEV), and ground state atomic energies (GSAEs).

    Option 3: Custom torch.nn.Module

    For maximum flexibility, inherit from torch.nn.Module and manually compose the components.

    # Option 1: Simple factory
    from torchani.arch import simple_ani
    model = simple_ani(("H", "C", "N", "O", "S"), lot="wb97x-631gd")
    
    # Option 2: Assembler
    import torchani
    asm = torchani.arch.Assembler()
    asm.set_symbols(("H", "C", "N", "O"))
    asm.set_aev_computer(radial="ani2x", angular="ani2x", strategy="cuaev")
    asm.set_atomic_networks(ctor="ani2x")
    asm.set_gsaes_as_self_energies("wb97x-631gd")
    model = asm.assemble()
    
    # Option 3: Custom Module
    import torchani
    from torch.nn import Module
    
    class Model(Module):
        def __init__(self):
            super().__init__()
            self.converter = torchani.nn.SpeciesConverter("...")
            self.neighborlist = torchani.neighbors.AllPairs("...")
            self.aevc = torchani.aev.AEVComputer("...")
            self.nn = torchani.nn.ANINetworks("...")
            self.shifter = torchani.sae.SelfEnergy("...")
    
        def forward(self, atomic_nums, coords, cell, pbc):
            idxs = self.converter(atomic_nums)
            cutoff = self.aevc.radial.cutoff
            neighbors = self.neighborlist(cutoff, idxs, coords, cell, pbc)
            aevs = self.aevc.compute_from_neighbors(idxs, neighbors)
            return self.nn(idxs, aevs) + self.shifter(idxs)
    
    model = Model()
  11. Install Torchani on an HPC cluster

    main

    When working on an HPC cluster, you must first start an interactive session with GPU access.

    Example session commands:

    • Hipergator: srun -p gpu --ntasks=1 --cpus-per-task=2 --gpus=geforce:1 --time=02:00:00 --mem=10gb --pty -u bash -i
    • Bridges2: srun -p GPU-small --ntasks=1 --cpus-per-task=5 --gpus=1 --time=02:00:00 --mem=20gb --pty -u bash -i
    • Expanse: srun -p gpu-shared --ntasks=1 --account=cwr109 --cpus-per-task=1 --gpus=1 --time=01:00:00 --mem=10gb --pty -u bash -i
    • Moria: srun --ntasks=1 --cpus-per-task=2 --gres=gpu:1 --time=02:00:00 --mem=10gb --pty -u bash -i

    Installation steps in the session:

    1. Create environment: conda create -f ./environment.yml
    2. Clone repo: git clone https://github.com/roitberg-group/torchani_sandbox.git
    3. Install base: pip install -v --no-deps --no-build-isolation --editable .
    4. Install with all-GPU support: pip install -v --no-deps --no-build-isolation --editable . --global-option="--ext-all-sms"