Basic calculations

GPUs and OpenMP threads

Select the device (CPU or GPU) and the number of threads.

Category
Basic calculations
APIs used
devicenum_threadscalc.device
Script
device_threads.py

Advance/OF-DFT is implemented with PyTorch and runs with OpenMP threads on CPUs and on NVIDIA GPUs (CUDA). The device is selected with device and the number of threads with num_threads.

device_threads.pyDownload
"""
Advance/OF-DFT example: run on a GPU or with OpenMP threads.

Copyright (C) 2026 AdvanceSoft Corporation, All rights reserved.
"""

import time

import torch
from ase.build import bulk

from aofdft.calculator import AOFDFTCalculator

VPS_DIR = "path/to/DFT_DATA19_AS/VPS"  # edit these two paths for your environment
PAO_DIR = "path/to/DFT_DATA19_AS/PAO"

# use the GPU when PyTorch can see one, otherwise the CPU
device = "cuda" if torch.cuda.is_available() else "cpu"

# 2x2x2 supercell of fcc Al (32 atoms)
atoms = bulk("Al", "fcc", a=4.05, cubic=True) * (2, 2, 2)

atoms.calc = AOFDFTCalculator(
    console      = False,
    logging_file = "al32.log",
    kin_type     = "AS26",
    kin_model    = "Crystal26",
    vps_dir      = VPS_DIR,
    pao_dir      = PAO_DIR,
    device       = device,  # "cpu", "cuda" or "cuda:1" (device ID from `nvidia-smi -L`)
    num_threads  = 8,       # OpenMP threads; None -> OMP_NUM_THREADS or all physical cores
)

start   = time.time()
energy  = atoms.get_potential_energy()
elapsed = time.time() - start

print(f"Device       : {atoms.calc.device}")
print(f"Atoms        : {len(atoms)}")
print(f"Total energy : {energy:.6f} eV")
print(f"Elapsed time : {elapsed:.1f} s")

Example output

text
Device       : cuda
Atoms        : 32
Total energy : -2146.131878 eV
Elapsed time : 11.4 s

Measured on an NVIDIA A30 (24 GB).

Notes

  • To use a GPU, install a CUDA build of PyTorch and set device="cuda". With several GPUs, look up the device ID with nvidia-smi -L and pass e.g. "cuda:1".
  • With num_threads=None (default), the value of the environment variable OMP_NUM_THREADS or MKL_NUM_THREADS is used if set, otherwise the default of PyTorch (usually all physical cores of the machine).
  • To switch the device after a calculation, assign to the property, e.g. calc.device = "cuda". The tensors held by the calculator are moved to the new device.
  • MPI is not supported. When running several calculations at once, adjust num_threads so that the total does not exceed the number of physical cores.
  • To take out the electron density as a NumPy array, move it to the CPU first: calc.rho.detach().cpu().numpy().
  • GPU memory usage grows with the number of FFT grid points and atoms. If the GPU runs out of memory, run on the CPU.