8000 PySCF v2.15.0 compatibility by MatthewRHermes · Pull Request #231 · pyscf/pyscf-forge · GitHub
[go: up one dir, main page]

Skip to content

PySCF v2.15.0 compatibility - #231

Merged
sunqm merged 3 commits into
masterfrom
pyscf_v2.15.0
Nov 11, 2026
Merged

sunqm merged 3 commits into
masterfrom
pyscf_v2.15.0

Conversation

@MatthewRHermes
@MatthewRHermes MatthewRHermes commented Nov 6, 2026 •
Copy link
Copy Markdown
Collaborator

Fix PySCF-Forge tests for PySCF 2.15.0

PySCF 2.15.0 is now on pip, and Forge CI installs it. With 2.15.0, one Forge unittest fails:
nac/test/test_tduks_sf.py::KnownValues::test_against_cache_refs. This PR fixes that test,
and adds an agent-recipe template describing the procedure for future PySCF core version upgrades.

TL;DR

pyscf/pyscf#2702 and pyscf/pyscf#3304 were affecting TDUKS-SF NACs at the time some reference data in unittests were generated. With those errors fixed, those reference points had to be regenerated. Nothing else broke.

Changes

  • nac/test/test_tduks_sf.py (eaf579b): the HF reference arrays in this test were produced with
    the v2.14.0 lib.krylov, whose UCPHF Z-vector solve stopped with a true residual of about 2e-5
    although the requested tolerance was 1e-8. Later core changes to lib.krylov and scf/ucphf.py
    (Prevent premature Krylov termination in CPHF and UCPHF solves pyscf#3334, Add per-rhs solve for krylov hard cases pyscf#3384, krylov: use the overlap of the trial vectors in the projected system pyscf#3549) make the solve converge properly. That
    moves the HF NAC by 2.5e-6, far outside the test's atol=1e-8. In addition, at the default SCF
    conv_tol (1e-9), tightening the SCF moves the NAC by up to 1e-6, so atol=1e-8 was below the
    noise floor of the SCF anyway. I decided to fix the test rather than core:

    • converge the SCF to conv_tol=1e-12;
    • regenerate all four reference arrays with PySCF 2.15.0;
    • loosen atol from 1e-8 to 1e-7.

    As a result, this test now fails against PySCF <= 2.14.0.

  • agent-recipes/ (4e04ac0): a README.md and a template, skills/updating-pyscf-core.template.md,
    describing how to triage and fix Forge unittest breakage after a PySCF core release.

Checks run by Claude Code (not independently verified by me)

Forge at eaf579b; PySCF core at v2.15.0-7-gc605e7af0 (a local checkout of v2.15.0 plus a few
later commits, none touching C code beyond comments).

  • CI on 2.15.0 before the fix. Claude read the CI logs of Migrate molecular LASCI and LASSCF to PySCF-Forge #230, a PR that was opened by
    mistake but which ran Forge CI against pip pyscf-2.15.0
    (run 42126224679). All three
    linux-build jobs (Python 3.9, 3.10, 3.12) had exactly one failure, test_against_cache_refs
    (e.g. 3.12: 1 failed, 588 passed, 9 skipped).

  • _slow tests. cd pyscf && pytest -k _slow (excluded from CI): 16 passed in 25 min.

  • Which NAC is correct. Claude solved the Z-vector system for all four test cases (478 unknowns;
    condition number 8 to 17) with a direct dense solve, and compared (max abs NAC difference):

    Compared HF (both use_etfs) B3LYP (both use_etfs)
    core 2.15 krylov vs. direct 1.0e-8 1.6e-10
    v2.14.0 krylov vs. direct 2.5e-6 5.6e-9
    old refs vs. direct 2.5e-6 9e-10
    old refs vs. v2.14.0 krylov 4e-11 5e-9
    direct, SCF conv_tol=1e-12 vs. 1e-9 1.1e-6 2.7e-7
  • Fixed test. pytest nac/test/test_tduks_sf.py: 2 passed. With the v2.14.0 lib.krylov
    swapped in by the pytest plugin below, test_against_cache_refs fails as expected (max abs
    difference 2.5e-6).

pytest plugin swapping in the v2.14.0 lib.krylov

Put this in a directory D together with linalg_helper_v2140.py
(git show v2.14.0:pyscf/lib/linalg_helper.py in a PySCF core checkout), then run
PYTHONPATH=D pytest -p oldkrylov_plugin nac/test/test_tduks_sf.py.

import importlib.util, os, pyscf.lib, pyscf.lib.linalg_helper as lh
spec = importlib.util.spec_from_file_location(
    'linalg_helper_v2140', os.path.join(os.path.dirname(__file__), 'linalg_helper_v2140.py'))
old = importlib.util.module_from_spec(spec); spec.loader.exec_module(old)
def krylov(*args, **kwargs):
    kwargs.pop('lindep', None)
    return old.krylov(*args, **kwargs)
lh.krylov = pyscf.lib.krylov = krylov
Script comparing Z-vector solvers (tight_cphf.py)

Expects linalg_helper_v2140.py next to it, and testdir pointing at pyscf/nac/test.

'''Which NAC is closer to the converged answer for test_tduks_sf.py::test_against_cache_refs?

For each of the 4 cases in the test (HF/B3LYP x use_etfs), compute the NAC with the UCPHF
Z-vector solved in several ways, by swapping `ucphf.solve` as seen from pyscf.nac.tduks_sf:

  default   : as in the test (core lib.krylov, tol=cphf_conv_tol=1e-8, lindep=max(tol**2,eps))
  old214    : v2.14.0 lib.krylov, tol=1e-8, no lindep kwarg (what the refs were made with)
  tight     : core lib.krylov, tol=1e-12, max_cycle=200
  direct    : dense solve of (1 + diag(1/e_ai) V) z = b, V built column by column from fvind

and also 'direct' with the SCF converged to conv_tol=1e-12 (test uses the default 1e-9), to
see how much of the ref-vs-new difference is below the SCF noise floor anyway.

Assumptions: test geometry/basis/grids unchanged; level_shift=0, s1=None (as tduks_sf calls it).
'''
import os, sys, time, importlib.util
import numpy as np
from pyscf import dft, lib
from pyscf.scf import ucphf
import pyscf.nac.tduks_sf as packaged_nac

here = os.path.dirname(os.path.abspath(__file__))
testdir = '/home/herme068/gits/pyscf_ext/pyscf-forge_pyscf_v2.15.0/pyscf/nac/test'
sys.path.insert(0, testdir)
import test_tduks_sf as T

spec = importlib.util.spec_from_file_location('linalg_helper_v2140',
                                              os.path.join(here, 'linalg_helper_v2140.py'))
old = importlib.util.module_from_spec(spec); spec.loader.exec_module(old)

orig_solve = ucphf.solve
info = {}

def setup(mo_energy, mo_occ, h1):
    occa, occb = mo_occ[0] > 0, mo_occ[1] > 0
    e_ai = np.hstack(((mo_energy[0][~occa,None] - mo_energy[0][occa]).ravel(),
                      (mo_energy[1][~occb,None] - mo_energy[1][occb]).ravel()))
    nova = (~occa).sum() * occa.sum()
    b = -np.hstack((h1[0].ravel(), h1[1].ravel())) / e_ai
    shapes = (((~occa).sum(), occa.sum()), ((~occb).sum(), occb.sum()))
    return e_ai, nova, b, shapes

def unpack(x, nova, shapes):
    return x[:nova].reshape(shapes[0]), x[nova:].reshape(shapes[1])

def residual(fvind, e_ai, b, x):
    return np.linalg.norm(x + fvind(x[None]).ravel() / e_ai - b)

def make_solve(mode):
    def solve(fvind, mo_energy, mo_occ, h1, s1=None, max_cycle=50, tol=1e-9, **kw):
        assert s1 is None
        e_ai, nova, b, shapes = setup(mo_energy, mo_occ, h1)
        aop = lambda x: np.asarray([fvind(xi[None]).ravel() for xi in x]) / e_ai
        t0 = time.time()
        if mode == 'default':
            z = orig_solve(fvind, mo_energy, mo_occ, h1, max_cycle=max_cycle, tol=tol, **kw)[0]
            x = np.hstack((z[0].ravel(), z[1].ravel()))
        elif mode == 'old214':
            x = old.krylov(aop, b[None], tol=tol, max_cycle=max_cycle, hermi=False)[0]
        elif mode == 'tight':
            x = lib.krylov(aop, b[None], tol=1e-12, max_cycle=200,
                           lindep=np.finfo(float).eps, hermi=False)[0]
        elif mode == 'direct':
            n = b.size
            M = np.eye(n)
            for i in range(n):
                ei = np.zeros(n); ei[i] = 1
                M[:, i] += fvind(ei[None]).ravel() / e_ai
            x = np.linalg.solve(M, b)
            info['cond'] = np.linalg.cond(M)
        info['resid'] = residual(fvind, e_ai, b, x)
        info['n'] = b.size
        info['t'] = time.time() - t0
        return unpack(x, nova, shapes), None
    return solve

def nac_for(xc, use_etfs, mode, scf_tol=None):
    mol = T.build_demo_molecule()
    mf = dft.UKS(mol); mf.xc = xc
    if scf_tol is not None:
        mf.conv_tol = scf_tol
    mf.kernel()
    solved = T.solve_shared_tddft(mf, extype=1, collinear_samples=50)
    td = T.build_td_object(mf, solved, extype=1, collinear_samples=50, xy_format='new')
    ucphf.solve = make_solve(mode)
    try:
        v = packaged_nac.NAC(td).kernel(state_I=1, state_J=3, use_etfs=use_etfs, ediff=False)
    finally:
        ucphf.solve = orig_solve
    return v

cases = [('HF', True, T.HF_REF_ETF), ('HF', False, T.HF_REF_FULL),
         ('B3LYP', True, T.B3LYP_REF_ETF), ('B3LYP', False, T.B3LYP_REF_FULL)]
runs = [('default', None), ('old214', None), ('tight', None), ('direct', None),
        ('direct', 1e-12)]

results = {}
for xc, etf, ref in cases:
    print(f'\n=== {xc} use_etfs={etf} ===', flush=True)
    vals = {}
    for mode, scf_tol in runs:
        key = mode if scf_tol is None else f'{mode}+scf{scf_tol:.0e}'
        v = nac_for(xc, etf, mode, scf_tol)
        if np.abs(-v - ref).max() < np.abs(v - ref).max():
            v = -v
        vals[key] = v
        extra = f" cond={info['cond']:.2e}" if 'cond' in info and mode == 'direct' else ''
        print(f"  {key:16s} n={info['n']} |resid|={info['resid']:.2e} t={info['t']:.1f}s{extra}"
              f"  max|v-ref|={np.abs(v-ref).max():.3e}", flush=True)
        info.clear()
    d = vals['direct']
    print('  max|v - direct| :')
    for k, v in vals.items():
        print(f'    {k:16s} {np.abs(v-d).max():.3e}')
    print(f'    {"ref":16s} {np.abs(ref-d).max():.3e}')
    results[(xc, etf)] = dict(vals, ref=ref)

np.save(os.path.join(here, 'tight_cphf_results.npy'), results, allow_pickle=True)

This description was drafted with Claude Code. The results in the "Checks run by Claude Code"
section were obtained by Claude and were not re-run by me.

🤖 Generated with Claude Code

MatthewRHermes and others added 3 commits November 6, 2026 11:55
test_tduks_sf.py::test_against_cache_refs fails against PySCF 2.15.0.
The HF reference arrays were produced with the v2.14.0 lib.krylov,
whose UCPHF Z-vector solve stopped with a true residual of about 2e-5
despite the requested tol of 1e-8. Core's later krylov/UCPHF changes
(#3334, #3384, #3549) converge properly and move the HF NAC by 2.5e-6,
far outside the test's atol of 1e-8.

I chose to fix the test rather than core:
- Converge the SCF to conv_tol=1e-12. At the default (1e-9) the NAC
  itself shifts by up to 1e-6 when the SCF is tightened, so an atol of
  1e-8 was below the SCF noise floor.
- Regenerate all four reference arrays with PySCF 2.15.0.
- Loosen atol from 1e-8 to 1e-7.

This test will fail against PySCF <= 2.14.0 (HF off by 2.5e-6).

Checks run by Claude Code (not independently re-run by me), forge at
this commit, PySCF core at v2.15.0-7-gc605e7af0:
- For all four cases, Claude solved the Z-vector system (478 unknowns,
  condition number 8-17) by a direct dense solve. Core 2.15's krylov
  agrees with it to 1e-8 (HF) and 2e-10 (B3LYP). The old refs match
  the v2.14.0 krylov to 5e-9 but are off the direct solve by 2.5e-6
  (HF). The B3LYP refs were within 1e-9 of the direct solve.
- pytest nac/test/test_tduks_sf.py: 2 passed. With the v2.14.0
  lib.krylov swapped in by a pytest plugin, test_against_cache_refs
  fails as expected (max abs diff 2.5e-6).

Commit message drafted with Claude Code; the checks above were run by
Claude and were not re-run by me.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reference arrays in test_tduks_sf.py were regenerated in eaf579b
with PySCF 2.15.0's packaged NAC, not the cache implementation, so the
printed note no longer described where they came from.

Commit drafted with Claude Code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MatthewRHermes MatthewRHermes added the housekeeping Enforcement of code rules, technical maintenance, and similar tedium label Nov 6, 2026
@MatthewRHermes
MatthewRHermes requested a review from sunqm November 6, 2026 19:41
MatthewRHermes added a commit that referenced this pull request Nov 9, 2026
Since numpy 2.5, np.linalg.eig returns complex128 eigenvalues and
eigenvectors for a real input matrix even when every eigenvalue is
real (numpy 2.4.6 still returns float64). The reference helpers in the
spin-flip gradient and NAC tests diagonalize the Casida matrix with
eig and pass the eigenvectors on as X/Y amplitudes, so with numpy 2.5
the gradient code fails with "_UFuncOutputCastingError: Cannot cast
ufunc 'add' output from dtype('complex128') to dtype('float64')".
This was hidden in CI by the scipy<1.16 pin, which kept numpy below
2.5 (scipy 1.15 does not support numpy 2.5).

The helpers now assert that the eigenvectors are real and take the
real part. eig is kept rather than eigh because the SF-TDDFT Casida
matrix is not symmetric.

Checks run by Claude Code (not independently verified by me): CI run
42521343348 on the previous commit failed 20 tests on Python 3.12
(numpy 2.5.4, scipy 1.18.1) with the error above, in
grad/test/test_sftda_grad.py, grad/test/test_sftddft_grad.py,
nac/test/test_batch_grad_nac_sf.py and nac/test/test_tduks_sf.py.
With this change, those four files were run locally (`pytest -k 'not
_slow' -W error::numpy.exceptions.ComplexWarning`) under both numpy
2.5.4 / scipy 1.18.1 and numpy 2.3.5 / scipy 1.17.1, with PySCF core
v2.15.0-7: 20 passed, 1 failed in each. The failure is
nac/test/test_tduks_sf.py::KnownValues::test_against_cache_refs, the
PySCF 2.15 reference-value issue addressed in #231.

Commit message drafted with Claude Code; the local test results above
were not re-run by me.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sunqm
sunqm merged commit 8583e4f into master Nov 11, 2026
12 checks passed
@sunqm
sunqm deleted the pyscf_v2.15.0 branch November 11, 2026 21:11
MatthewRHermes added a commit that referenced this pull request Nov 11, 2026
)

* CI: remove the scipy<1.16 pin

The pin was added in #92 (aa6b613, 7e798f8) with the commit title
"Adjust unittest due to Scipy 1.16 compatibility issue", but no test
was changed and the PR thread does not say which test failed. scipy
1.16 requires Python >= 3.11, so of the current CI matrix (3.9, 3.10,
3.12) the pin only affects the 3.12 job.

Checks run by Claude Code (not independently verified by me): the CI
test set (git-tracked test files, `pytest -k 'not _slow'` from
pyscf/) was run locally on master e4fabd5 with Python 3.12, scipy
1.17.1, numpy 2.3.5, PySCF core v2.15.0-7 (MKL BLAS). Result: 588
passed, 9 skipped, 1 failed. The failure,
nac/test/test_tduks_sf.py::KnownValues::test_against_cache_refs, is a
PySCF 2.15 Krylov-solver reference-value issue that is addressed in
#231 and is unrelated to scipy. No scipy warnings were emitted. CI's
pip wheels use OpenBLAS rather than MKL; this push is to check that
configuration.

Commit message drafted with Claude Code; the local test results above
were not re-run by me.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Make sf grad/NAC test helpers robust to numpy 2.5 eig

Since numpy 2.5, np.linalg.eig returns complex128 eigenvalues and
eigenvectors for a real input matrix even when every eigenvalue is
real (numpy 2.4.6 still returns float64). The reference helpers in the
spin-flip gradient and NAC tests diagonalize the Casida matrix with
eig and pass the eigenvectors on as X/Y amplitudes, so with numpy 2.5
the gradient code fails with "_UFuncOutputCastingError: Cannot cast
ufunc 'add' output from dtype('complex128') to dtype('float64')".
This was hidden in CI by the scipy<1.16 pin, which kept numpy below
2.5 (scipy 1.15 does not support numpy 2.5).

The helpers now assert that the eigenvectors are real and take the
real part. eig is kept rather than eigh because the SF-TDDFT Casida
matrix is not symmetric.

Checks run by Claude Code (not independently verified by me): CI run
42521343348 on the previous commit failed 20 tests on Python 3.12
(numpy 2.5.4, scipy 1.18.1) with the error above, in
grad/test/test_sftda_grad.py, grad/test/test_sftddft_grad.py,
nac/test/test_batch_grad_nac_sf.py and nac/test/test_tduks_sf.py.
With this change, those four files were run locally (`pytest -k 'not
_slow' -W error::numpy.exceptions.ComplexWarning`) under both numpy
2.5.4 / scipy 1.18.1 and numpy 2.3.5 / scipy 1.17.1, with PySCF core
v2.15.0-7: 20 passed, 1 failed in each. The failure is
nac/test/test_tduks_sf.py::KnownValues::test_against_cache_refs, the
PySCF 2.15 reference-value issue addressed in #231.

Commit message drafted with Claude Code; the local test results above
were not re-run by me.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pwscf: replace ndarray.shape assignment with reshape

Setting the shape attribute of an array is deprecated in numpy 2.5.
On Python 3.12 CI (numpy 2.5.4), the seven such assignments in
pbc/pwscf produced about 2,850 DeprecationWarnings. Each is replaced
with reshape():

- pw_helper.py: the slices of the DIIS result are reshaped as they are
  assigned; the arrays reshaped in place were fresh slices, so nothing
  else saw the old shape.
- krks.py (coarse_to_dense_grid): reshape the input instead of
  reshaping a view of it, and return a reshaped result. A caller-
  supplied out_xr is still written but no longer has its shape
  changed; no caller currently passes out_xr.
- kpt_symm.py (get_C_from_ibz2bz_info): apply the real-space phases
  through a 4D view of out instead of temporarily reshaping out. out is
  created C-contiguous just above, so the reshape is a view and the
  writes still land in the caller's buffer.

Unlike shape assignment, reshape() silently copies when a view is
impossible. Where a copy would give wrong results (the phases in
kpt_symm.py would be lost, and the result in krks.py would no longer
be out_xr), an assert with np.may_share_memory checks that the
reshape returned a view.

Checks run by Claude Code (not independently verified by me): the 11
tracked test files in pbc/pwscf/test were run locally (`pytest -k 'not
_slow'`) with PySCF core v2.15.0-7, under numpy 2.5.4 / scipy 1.18.1
with `-W "error:Setting the shape:DeprecationWarning"` and under numpy
2.3.5 / scipy 1.17.1: 24 passed, 1 skipped, 1 deselected in each. The
realspace branch of get_C_from_ibz2bz_info, which holds the kpt_symm.py
assert, ran 270 times; no test passes out_xr to coarse_to_dense_grid.

Commit message drafted with Claude Code; the local test results above
were not re-run by me.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

housekeeping Enforcement of code rules, technical maintenance, and similar tedium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

0