Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions model/examples/cpp/cpp_integration/prepare_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
import torch
from pyscf.dft import gen_grid
from skala.functional.traditional import LDA
from skala.pyscf.features import generate_features
from skala.pyscf.evaluation import FeatureSpec
from skala.pyscf.model_chunking import evaluate_model_features
from skala_model import SkalaFunctional

from pyscf import dft, gto
Expand Down Expand Up @@ -41,8 +42,8 @@ def main() -> None:
grid = gen_grid.Grids(molecule)
grid.level = 3
grid.build(sort_grids=False)
features = generate_features(
molecule, dm, grid, features=set(SkalaFunctional.features)
features = evaluate_model_features(
molecule, dm, grid, FeatureSpec(SkalaFunctional.features)
)

# Save all features as individual .pt files.
Expand Down
95 changes: 87 additions & 8 deletions skala/src/skala/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

"""Names of built-in molecular features."""

from enum import Enum
from typing import TYPE_CHECKING, TypeAlias
from collections.abc import Iterable, Iterator
from enum import StrEnum
from typing import TypeAlias

if TYPE_CHECKING:
from torch import Tensor
from torch import Tensor


class Feature(str, Enum): # noqa: UP042 - Python 3.10-compatible StrEnum
"""String-compatible names of features understood by Skala."""
class Feature(StrEnum):
"""features understood by Skala."""

DENSITY = "density"
GRAD = "grad"
Expand All @@ -23,7 +23,86 @@ class Feature(str, Enum): # noqa: UP042 - Python 3.10-compatible StrEnum
ATOMIC_GRID_SIZE_BOUND_SHAPE = "atomic_grid_size_bound_shape"
COARSE_0_ATOMIC_COORDS = "coarse_0_atomic_coords"

__str__ = str.__str__

AO_FEATURES = frozenset(
{
Feature.DENSITY,
Feature.GRAD,
Feature.KIN,
Feature.LAPL,
}
)

FeatureMap: TypeAlias = dict[Feature, "Tensor"]

def ao_derivative_order(features: Iterable[Feature]) -> int:
"""Return the highest AO derivative order required by the features.

Args:
features: Molecular features to inspect.

Returns:
Required AO derivative order, or zero when no AO feature is present.
"""
ao_features = AO_FEATURES & set(features)
if Feature.LAPL in ao_features:
return 2
if ao_features & {Feature.GRAD, Feature.KIN}:
return 1
return 0


class AOFeatureSpec:
"""Normalized non-empty set of AO-derived features."""

def __init__(self, features: Iterable[Feature]) -> None:
self._features = frozenset(features)
unsupported = self._features - AO_FEATURES
if unsupported:
unsupported_names = ", ".join(
sorted(str(feature) for feature in unsupported)
)
raise ValueError(f"Unsupported AO features: {unsupported_names}")
if not self._features:
raise ValueError("At least one AO-derived feature must be selected.")

self._feature_slices: dict[Feature, slice] = {}
feature_index = 0
for feature, width in (
(Feature.DENSITY, 1),
(Feature.GRAD, 3),
(Feature.KIN, 1),
(Feature.LAPL, 1),
):
if feature in self._features:
self._feature_slices[feature] = slice(
feature_index, feature_index + width
)
feature_index += width
self._nfeats = feature_index

def __contains__(self, feature: object) -> bool:
return feature in self._features

def __iter__(self) -> Iterator[tuple[Feature, slice]]:
return iter(self._feature_slices.items())

def __eq__(self, other: object) -> bool:
if not isinstance(other, AOFeatureSpec):
return NotImplemented
return self._features == other._features

def __hash__(self) -> int:
return hash(self._features)

@property
def nderiv(self) -> int:
"""Return the required AO derivative order."""
return ao_derivative_order(self._features)

@property
def nfeats(self) -> int:
"""Return the number of packed scalar feature channels."""
return self._nfeats


FeatureMap: TypeAlias = dict[Feature, Tensor]
153 changes: 36 additions & 117 deletions skala/src/skala/gpu4pyscf/gradients.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

"""Modification of PySCF nuclear gradient object to work with Skala functional."""

import logging
from collections.abc import Iterator
from typing import Any

import cupy as cp
Expand All @@ -15,68 +15,31 @@
from gpu4pyscf.scf.hf import SCF
from torch.utils.dlpack import from_dlpack

import skala.pyscf.features as feature
from pyscf import gto
from skala.dispersion import DFTD3Dispersion
from skala.features import Feature, FeatureMap
from skala.features import Feature
from skala.functional.base import ExcFunctionalBase
from skala.pyscf.gradient_core import (
contract_ao_derivative_block,
feature_derivatives,
grid_derivative_block,
assemble_nuclear_gradient,
evaluate_nuclear_feature_derivatives,
)

LOG = logging.getLogger(__name__)


def veff_and_expl_nuc_grad(
def _veff_and_expl_nuc_grad(
functional: ExcFunctionalBase,
mol: gto.Mole,
grid: dft.Grids,
rdm1: torch.Tensor,
nuc_grad_feats: set[Feature] | None = None,
*,
max_memory_in_mb: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
returns:
- 1st tuple argument: the effective potential per atom (not the matrix!)
- 2nd tuple argument: explicit contributions to the nuclear gradient
"""

SUPPORTED_FEATS = {
Feature.DENSITY,
Feature.GRAD,
Feature.KIN,
Feature.GRID_COORDS,
Feature.GRID_WEIGHTS,
Feature.ATOMIC_GRID_WEIGHTS,
Feature.COARSE_0_ATOMIC_COORDS,
}

if nuc_grad_feats is None: # generate feature list from functional features
nuc_grad_feats = set(functional.features)

# Integer-valued features have no nuclear gradient — always discard them
nuc_grad_feats.discard(Feature.ATOMIC_GRID_SIZES)
nuc_grad_feats.discard(Feature.ATOMIC_GRID_SIZE_BOUND_SHAPE)

# check for unsupported features
unsupported_feats = {feat for feat in nuc_grad_feats if feat not in SUPPORTED_FEATS}
if unsupported_feats != set():
raise NotImplementedError(
f"Not supported features for nuclear gradient: {unsupported_feats}"
)

LOG.debug("nuc_grad_feats = %s", nuc_grad_feats)

# determine the maximum ao derivative needed
if Feature.GRAD in nuc_grad_feats or Feature.KIN in nuc_grad_feats:
ao_deriv = 2
elif Feature.DENSITY in nuc_grad_feats:
ao_deriv = 1
else:
ao_deriv = 0

# Get the derivatives of the weights per atom and make sure the grid is blocked per atom, no padding, etc.
coord_list = []
weight_list = []
for coords, weight in grids_noresponse_cc(grid):
Expand All @@ -86,79 +49,31 @@ def veff_and_expl_nuc_grad(
grid_ = grid.copy()
grid_.coords = cp.concatenate(coord_list)
grid_.weights = cp.concatenate(weight_list)
mol_feats = feature.generate_features(
mol, rdm1, grid_, set(functional.features), gpu=True
ao_deriv, derivatives = evaluate_nuclear_feature_derivatives(
functional,
mol,
grid_,
rdm1,
nuc_grad_feats,
max_memory_in_mb=max_memory_in_mb,
)

# Discard atomic_grid_weights from VJP features: d(atomic_grid_weights)/dR = 0
# because they are raw quadrature weights that depend only on the radial/angular
# grid rule, not on nuclear positions. They still pass through as other_feats.
nuc_grad_feats.discard(Feature.ATOMIC_GRID_WEIGHTS)

# Get required derivatives
nuc_feats = {feat: mol_feats[feat] for feat in nuc_grad_feats}
other_feats = {
feat: mol_feats[feat] for feat in mol_feats if feat not in nuc_grad_feats
}

def exc_feat_func(differentiable_features: FeatureMap) -> torch.Tensor:
return functional.get_exc(differentiable_features | other_feats)

dExc = feature_derivatives(exc_feat_func, nuc_feats)

LOG.debug("autograd gradients for nuclear features done")

nao = rdm1.shape[-1]
veff = torch.zeros((2, 3, nao, nao), dtype=rdm1.dtype, device=rdm1.device)
nuc_grad = torch.zeros((mol.natm, 3), dtype=rdm1.dtype, device=rdm1.device)

atm_start = 0
for atm_id, (coords, weight, weight1) in enumerate(grids_response_cc(grid)):
mask = dft.gen_grid.make_mask(mol, coords)
ao = from_dlpack(
dft.numint.eval_ao(
mol,
coords,
deriv=ao_deriv,
non0tab=mask, # cutoff=grid.cutoff
def atom_grid_blocks() -> Iterator[tuple[torch.Tensor, int, torch.Tensor]]:
for coords, weight, weight1 in grids_response_cc(grid):
mask = dft.gen_grid.make_mask(mol, coords)
ao = from_dlpack(
dft.numint.eval_ao(
mol,
coords,
deriv=ao_deriv,
non0tab=mask,
)
)
)
if ao_deriv == 0:
ao = ao[None, ...]
atm_end = atm_start + weight.shape[0]
dExc_atm = grid_derivative_block(dExc, atm_start, atm_end)

# Calculate the contribution to veff for this atomic grid
veff_atm = contract_ao_derivative_block(ao, dExc_atm)

if Feature.GRID_COORDS in dExc_atm:
# also add the explicit grid coordinate dependence
nuc_grad[atm_id] += dExc_atm[Feature.GRID_COORDS].sum(dim=0)

if Feature.GRID_WEIGHTS in dExc_atm:
Exc_dgw = dExc_atm[Feature.GRID_WEIGHTS]
nuc_grad += from_dlpack(weight1) @ Exc_dgw
# add the grid coordinate dependence via the density-like quantities to the nuclear gradient
# we get those from the veff block. This tends to largely cancel with the grid_weights derivative,
# so that's why we include it here.
if len(rdm1.shape) == 2:
nuc_grad[atm_id] += torch.einsum("sxpq,qp->x", veff_atm, rdm1)
else:
nuc_grad[atm_id] += torch.einsum("sxpq,sqp->x", veff_atm, rdm1) * 2

veff += veff_atm
atm_start = atm_end

if Feature.COARSE_0_ATOMIC_COORDS in nuc_grad_feats:
nuc_grad += dExc[Feature.COARSE_0_ATOMIC_COORDS]

# finalize
if len(rdm1.shape) == 2:
veff = veff.sum(0) / 2

LOG.debug("veff and explicit components for nuclear gradient calculated")
if ao_deriv == 0:
ao = ao[None, ...]
yield ao, weight.shape[0], from_dlpack(weight1)

return -veff, nuc_grad
return assemble_nuclear_gradient(derivatives, rdm1, mol.natm, atom_grid_blocks())


def nuc_grad_from_veff(
Expand Down Expand Up @@ -208,12 +123,13 @@ def energy_ee(
if dm is None:
dm = self.base.make_rdm1()

veff, self.veff_nuc_grad_ = veff_and_expl_nuc_grad(
veff, self.veff_nuc_grad_ = _veff_and_expl_nuc_grad(
self.functional,
mol=mol,
grid=self.grids,
rdm1=from_dlpack(dm),
nuc_grad_feats=self.nuc_grad_feats,
max_memory_in_mb=int(self.base.max_memory),
)
veff_grad = (
2 * nuc_grad_from_veff(mol, veff, from_dlpack(dm)).detach().cpu().numpy()
Expand All @@ -240,12 +156,13 @@ def grad_elec(

if self.veff_nuc_grad_ is None:
dm = self.base.make_rdm1()
_, self.veff_nuc_grad_ = veff_and_expl_nuc_grad(
_, self.veff_nuc_grad_ = _veff_and_expl_nuc_grad(
self.functional,
mol=self.mol,
grid=self.grids,
rdm1=from_dlpack(dm),
nuc_grad_feats=self.nuc_grad_feats,
max_memory_in_mb=int(self.base.max_memory),
)
veff_nuc_grad = self.veff_nuc_grad_
if veff_nuc_grad is None:
Expand Down Expand Up @@ -314,12 +231,13 @@ def energy_ee(
if dm is None:
dm = self.base.make_rdm1()

veff, self.veff_nuc_grad_ = veff_and_expl_nuc_grad(
veff, self.veff_nuc_grad_ = _veff_and_expl_nuc_grad(
self.functional,
mol=mol,
grid=self.grids,
rdm1=from_dlpack(dm),
nuc_grad_feats=self.nuc_grad_feats,
max_memory_in_mb=int(self.base.max_memory),
)
veff_grad = (
2 * nuc_grad_from_veff(mol, veff, from_dlpack(dm)).detach().cpu().numpy()
Expand All @@ -346,12 +264,13 @@ def grad_elec(

if self.veff_nuc_grad_ is None:
dm = self.base.make_rdm1()
_, self.veff_nuc_grad_ = veff_and_expl_nuc_grad(
_, self.veff_nuc_grad_ = _veff_and_expl_nuc_grad(
self.functional,
mol=self.mol,
grid=self.grids,
rdm1=from_dlpack(dm),
nuc_grad_feats=self.nuc_grad_feats,
max_memory_in_mb=int(self.base.max_memory),
)
veff_nuc_grad = self.veff_nuc_grad_
if veff_nuc_grad is None:
Expand Down
Loading
Loading