From 38c9594c291643d7a5087fd59a9b52003985d9f1 Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 21:14:58 +0100 Subject: [PATCH 01/26] ao_tc_eff_map: cast the AO cache index in ior() to 32 bits (pre-existing, from #437) The cache index ii is a 32-bit packed value (six bits per AO); the size_t conversion made i, j, k, l 64-bit, and gfortran 16 rejects mixed-kind ior() arguments. Down-cast the index differences at the nine sites; no logic change. --- .../ao_tc_eff_map/map_integrals_eff_pot.irp.f | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/plugins/local/ao_tc_eff_map/map_integrals_eff_pot.irp.f b/plugins/local/ao_tc_eff_map/map_integrals_eff_pot.irp.f index a6afbca8..2220c6e5 100644 --- a/plugins/local/ao_tc_eff_map/map_integrals_eff_pot.irp.f +++ b/plugins/local/ao_tc_eff_map/map_integrals_eff_pot.irp.f @@ -57,9 +57,9 @@ !DIR$ FORCEINLINE call map_get(ao_tc_sym_two_e_pot_map, idx, integral) ii = l-ao_tc_sym_two_e_pot_cache_min - ii = ior( ishft(ii,6), k-ao_tc_sym_two_e_pot_cache_min) - ii = ior( ishft(ii,6), j-ao_tc_sym_two_e_pot_cache_min) - ii = ior( ishft(ii,6), i-ao_tc_sym_two_e_pot_cache_min) + ii = ior( ishft(ii,6), int(k-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior( ishft(ii,6), int(j-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior( ishft(ii,6), int(i-ao_tc_sym_two_e_pot_cache_min, 4)) ao_tc_sym_two_e_pot_cache(ii) = integral enddo enddo @@ -118,9 +118,9 @@ double precision function get_ao_tc_sym_two_e_pot(i, j, k, l, map) result(result ! tmp = 0.d0 else ii = l-ao_tc_sym_two_e_pot_cache_min - ii = ior(ii, k-ao_tc_sym_two_e_pot_cache_min) - ii = ior(ii, j-ao_tc_sym_two_e_pot_cache_min) - ii = ior(ii, i-ao_tc_sym_two_e_pot_cache_min) + ii = ior(ii, int(k-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior(ii, int(j-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior(ii, int(i-ao_tc_sym_two_e_pot_cache_min, 4)) if (iand(ii, -64) /= 0) then !DIR$ FORCEINLINE call two_e_integrals_index(i, j, k, l, idx) @@ -129,9 +129,9 @@ double precision function get_ao_tc_sym_two_e_pot(i, j, k, l, map) result(result tmp = tmp else ii = l-ao_tc_sym_two_e_pot_cache_min - ii = ior( ishft(ii,6), k-ao_tc_sym_two_e_pot_cache_min) - ii = ior( ishft(ii,6), j-ao_tc_sym_two_e_pot_cache_min) - ii = ior( ishft(ii,6), i-ao_tc_sym_two_e_pot_cache_min) + ii = ior( ishft(ii,6), int(k-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior( ishft(ii,6), int(j-ao_tc_sym_two_e_pot_cache_min, 4)) + ii = ior( ishft(ii,6), int(i-ao_tc_sym_two_e_pot_cache_min, 4)) tmp = ao_tc_sym_two_e_pot_cache(ii) endif endif From 318941b1858b54501908f22d964268e5c4abdc43 Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 21:14:58 +0100 Subject: [PATCH 02/26] ao_tc_eff_map: move the stray use sizet into the subroutine body, j1 (pre-existing, from #437) The size_t batch inserted 'use sizet' inside the continued argument list of get_cxcycz_j1(); no compiler accepts that. get_cxcycz_j1 declares integer(size_t) :: ii, so the statement belongs in its body (conventions.rst, placement of use sizet). --- plugins/local/ao_tc_eff_map/two_e_1bgauss_j1.irp.f | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plugins/local/ao_tc_eff_map/two_e_1bgauss_j1.irp.f b/plugins/local/ao_tc_eff_map/two_e_1bgauss_j1.irp.f index 6c493ef7..8dd9782a 100644 --- a/plugins/local/ao_tc_eff_map/two_e_1bgauss_j1.irp.f +++ b/plugins/local/ao_tc_eff_map/two_e_1bgauss_j1.irp.f @@ -238,10 +238,11 @@ double precision function env_gauss_2e_j1_schwartz(i, j, k, l) ! --- subroutine get_cxcycz_j1( dim1, cx, cy, cz & - use sizet , P1_center, P1_new, pp1, fact_p1, p1_inv, iorder_p & , Q1_center, Q1_new, qq1, fact_q1, q1_inv, iorder_q ) + use sizet + include 'utils/constants.include.F' implicit none From ebf3f50417f3fc4a2f2c7653768884d088914137 Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 21:14:58 +0100 Subject: [PATCH 03/26] ao_tc_eff_map: move the stray use sizet into the subroutine body, j2 (pre-existing, from #437) Same mangled insertion as two_e_1bgauss_j1.irp.f, in get_cxcycz_j2(). --- plugins/local/ao_tc_eff_map/two_e_1bgauss_j2.irp.f | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plugins/local/ao_tc_eff_map/two_e_1bgauss_j2.irp.f b/plugins/local/ao_tc_eff_map/two_e_1bgauss_j2.irp.f index 6752bd9c..926cf48b 100644 --- a/plugins/local/ao_tc_eff_map/two_e_1bgauss_j2.irp.f +++ b/plugins/local/ao_tc_eff_map/two_e_1bgauss_j2.irp.f @@ -241,10 +241,11 @@ double precision function env_gauss_2e_j2_schwartz(i, j, k, l) ! --- subroutine get_cxcycz_j2( dim1, cx, cy, cz & - use sizet , P1_center, P1_new, pp1, fact_p1, p1_inv, iorder_p & , Q1_center, Q1_new, qq1, fact_q1, q1_inv, iorder_q ) + use sizet + include 'utils/constants.include.F' implicit none From 16bb415065011532aa0e0d7cab53d64324ef6b9a Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 21:14:58 +0100 Subject: [PATCH 04/26] ao_tc_eff_map: pass size_t literals to compute_ao_tc_sym_two_e_pot_jl (pre-existing, from #437) The callee takes integer(size_t) arguments; the literal 1 at two call sites made gfortran infer 32-bit dummies and warn on the size_t l. Spell 1_size_t. --- plugins/local/ao_tc_eff_map/providers_ao_eff_pot.irp.f | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/local/ao_tc_eff_map/providers_ao_eff_pot.irp.f b/plugins/local/ao_tc_eff_map/providers_ao_eff_pot.irp.f index 1587f6fb..8d13fcf6 100644 --- a/plugins/local/ao_tc_eff_map/providers_ao_eff_pot.irp.f +++ b/plugins/local/ao_tc_eff_map/providers_ao_eff_pot.irp.f @@ -63,7 +63,7 @@ ! parallel-do because its result is already in the map (the ! pt2_omp pattern). allocate ( buffer_i(ao_num*ao_num), buffer_value(ao_num*ao_num) ) - call compute_ao_tc_sym_two_e_pot_jl(1,1,n_integrals,buffer_i,buffer_value) + call compute_ao_tc_sym_two_e_pot_jl(1_size_t,1_size_t,n_integrals,buffer_i,buffer_value) call insert_into_ao_tc_sym_two_e_pot_map(n_integrals,buffer_i,buffer_value) accu = accu + n_integrals deallocate ( buffer_i, buffer_value ) @@ -75,7 +75,7 @@ allocate ( buffer_i_t(ao_num*ao_num), buffer_value_t(ao_num*ao_num) ) !$OMP DO SCHEDULE(DYNAMIC,1) do l=2,ao_num - call compute_ao_tc_sym_two_e_pot_jl(1,l,n_integrals,buffer_i_t,buffer_value_t) + call compute_ao_tc_sym_two_e_pot_jl(1_size_t,l,n_integrals,buffer_i_t,buffer_value_t) !$OMP CRITICAL call insert_into_ao_tc_sym_two_e_pot_map(n_integrals,buffer_i_t,buffer_value_t) accu = accu + n_integrals From e07857e72b66e296a9ce720516dab9f05623a348 Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 21:14:58 +0100 Subject: [PATCH 05/26] bi_ort_ints: declare n_points4 shared in the DEFAULT(NONE) dgemm region (pre-existing, from #437) The size_t batch replaced 4*n_points_final_grid by the 32-bit local n_points4 in four dgemm calls without adding it to the SHARED clause. n_points4 is assigned before the region and only read inside it: SHARED is the only correct clause. --- plugins/local/bi_ort_ints/three_body_ijmk.irp.f | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/local/bi_ort_ints/three_body_ijmk.irp.f b/plugins/local/bi_ort_ints/three_body_ijmk.irp.f index 909fca17..9bf94d84 100644 --- a/plugins/local/bi_ort_ints/three_body_ijmk.irp.f +++ b/plugins/local/bi_ort_ints/three_body_ijmk.irp.f @@ -78,7 +78,7 @@ !$OMP PARALLEL & !$OMP DEFAULT (NONE) & !$OMP PRIVATE (k, i, j, m, n, ipoint, tmp_loc_1, tmp_loc_2, tmp_2d, tmp1, tmp2) & - !$OMP SHARED (mo_num, n_points_final_grid, & + !$OMP SHARED (mo_num, n_points_final_grid, n_points4, & !$OMP mos_l_in_r_array_transp, mos_r_in_r_array_transp, & !$OMP int2_grad1_u12_bimo_t, final_weight_at_r_vector, & !$OMP tmp_aux_1, tmp_aux_2, & From b7e81dc7d55af531da90e696b2679fd2bcd0286f Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 21:14:59 +0100 Subject: [PATCH 06/26] bi_ortho_mos: down-cast n_core_orb at the dgemm k argument (pre-existing, from #437) n_core_orb is integer(size_t) after the conversion; BLAS stays 32-bit. --- plugins/local/bi_ortho_mos/bi_density.irp.f | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/local/bi_ortho_mos/bi_density.irp.f b/plugins/local/bi_ortho_mos/bi_density.irp.f index 0b2ac8bd..159892f6 100644 --- a/plugins/local/bi_ortho_mos/bi_density.irp.f +++ b/plugins/local/bi_ortho_mos/bi_density.irp.f @@ -87,7 +87,7 @@ ! END_DOC PROVIDE mo_r_core_coef mo_l_core_coef - call dgemm( 'N', 'T', ao_num, ao_num, n_core_orb, 1.d0 & + call dgemm( 'N', 'T', ao_num, ao_num, int(n_core_orb, 4), 1.d0 & , mo_l_core_coef, size(mo_l_core_coef, 1), mo_r_core_coef, size(mo_r_core_coef, 1) & , 0.d0, TCSCF_bi_ort_core_dm_ao, size(TCSCF_bi_ort_core_dm_ao, 1) ) ! factor two because it is the total DM From 591cbbe33c7978305e8a054fce6890763b3ab972 Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 21:14:59 +0100 Subject: [PATCH 07/26] non_hermit_dav: use sizet inside bi_ortho_gram_schmidt (pre-existing, from #437) The procedure declares integer(size_t) in its body; the file-level use sizet is not hoisted into hand-written procedures (conventions.rst). --- plugins/local/non_hermit_dav/gram_schmit.irp.f | 1 + 1 file changed, 1 insertion(+) diff --git a/plugins/local/non_hermit_dav/gram_schmit.irp.f b/plugins/local/non_hermit_dav/gram_schmit.irp.f index cdc49ff8..f344331f 100644 --- a/plugins/local/non_hermit_dav/gram_schmit.irp.f +++ b/plugins/local/non_hermit_dav/gram_schmit.irp.f @@ -1,6 +1,7 @@ use sizet subroutine bi_ortho_gram_schmidt(wi,vi,n,ni,wk,wk_schmidt) + use sizet implicit none BEGIN_DOC ! you enter with a set of "ni" BI-ORTHONORMAL vectors of length "n" From d693cee4e9f86f719c7d8c12634a448f22b17af9 Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 21:14:59 +0100 Subject: [PATCH 08/26] non_hermit_dav: use sizet in the three hand-written procedures of project.irp.f (pre-existing, from #437) h_non_hermite, exp_tau_H and project_phi0 each declare integer(size_t) in their body; the file-level use sizet is not hoisted into them. --- plugins/local/non_hermit_dav/project.irp.f | 3 +++ 1 file changed, 3 insertions(+) diff --git a/plugins/local/non_hermit_dav/project.irp.f b/plugins/local/non_hermit_dav/project.irp.f index cce9ea67..3939a5bf 100644 --- a/plugins/local/non_hermit_dav/project.irp.f +++ b/plugins/local/non_hermit_dav/project.irp.f @@ -1,6 +1,7 @@ use sizet subroutine h_non_hermite(v,u,Hmat,a,N_st,sze) + use sizet implicit none BEGIN_DOC ! Template of routine for the application of H @@ -28,6 +29,7 @@ subroutine h_non_hermite(v,u,Hmat,a,N_st,sze) subroutine exp_tau_H(u,v,hmat,tau,et,N_st,sze) + use sizet implicit none BEGIN_DOC ! realises v = (1 - tau (H - et)) u @@ -44,6 +46,7 @@ subroutine exp_tau_H(u,v,hmat,tau,et,N_st,sze) end double precision function project_phi0(u,Hmat0,N_st,sze) + use sizet implicit none integer, intent(in) :: N_st integer(size_t), intent(in) :: sze From 7340201cd8c6b7e930d2c8063560e7aa7ae010c2 Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 21:15:04 +0100 Subject: [PATCH 09/26] tc_scf: log results through the yyjson API (pre-existing, from 5a721280) The TC-SCF plugin still wrote its JSON with json_unit/json_*_fmt, deleted when the result logging moved to a yyjson document. Start the document once with json_init('tc_scf') in the program and log the per-iteration values with json_add on /results/tc_scf/, following src/casscf_cipsi/casscf.irp.f. Fixed paths, last value wins: the per-iteration array is not recreated. lock_io/unlock_io and the convergence control flow are unchanged. --- plugins/local/tc_scf/rh_tcscf_diis.irp.f | 36 ++++++++++-------------- plugins/local/tc_scf/tc_scf.irp.f | 4 +-- 2 files changed, 16 insertions(+), 24 deletions(-) diff --git a/plugins/local/tc_scf/rh_tcscf_diis.irp.f b/plugins/local/tc_scf/rh_tcscf_diis.irp.f index 04aab8e8..66b5d4e6 100644 --- a/plugins/local/tc_scf/rh_tcscf_diis.irp.f +++ b/plugins/local/tc_scf/rh_tcscf_diis.irp.f @@ -7,6 +7,7 @@ subroutine rh_tcscf_diis() + use qp_json, only: json_add implicit none integer :: i, j, it @@ -216,45 +217,38 @@ subroutine rh_tcscf_diis() ! Write data in JSON file call lock_io - if (it == 1) then - write(json_unit, json_dict_uopen_fmt) - else - write(json_unit, json_dict_close_uopen_fmt) - endif - write(json_unit, json_int_fmt) ' iteration ', it - write(json_unit, json_real_fmt) ' SCF TC Energy ', etc_tot - write(json_unit, json_real_fmt) ' E(1e) ', etc_1e - write(json_unit, json_real_fmt) ' E(2e) ', etc_2e - write(json_unit, json_real_fmt) ' E(3e) ', etc_3e - write(json_unit, json_real_fmt) ' delta Energy ', e_delta - write(json_unit, json_real_fmt) ' DIIS error ', er_DIIS - write(json_unit, json_real_fmt) ' level_shift ', level_shift_tcscf - write(json_unit, json_int_fmtx) ' DIIS ', dim_DIIS - write(json_unit, json_real_fmt) ' Wall time (min)', (t1-t0)/60.d0 + call json_add('/results/tc_scf/iteration', it) + call json_add('/results/tc_scf/scf_tc_energy', etc_tot) + call json_add('/results/tc_scf/energy_1e', etc_1e) + call json_add('/results/tc_scf/energy_2e', etc_2e) + call json_add('/results/tc_scf/energy_3e', etc_3e) + call json_add('/results/tc_scf/delta_energy', e_delta) + call json_add('/results/tc_scf/diis_error', er_DIIS) + call json_add('/results/tc_scf/level_shift', level_shift_tcscf) + call json_add('/results/tc_scf/diis_size', dim_DIIS) + call json_add('/results/tc_scf/wall_time_min', (t1-t0)/60.d0) call unlock_io if(er_delta .lt. 0.d0) then call ezfio_set_tc_scf_tcscf_energy(etc_tot) call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) call ezfio_set_bi_ortho_mos_mo_r_coef(mo_r_coef) - write(json_unit, json_true_fmt) 'saved' + call json_add('/results/tc_scf/saved', .true.) else - write(json_unit, json_false_fmt) 'saved' + call json_add('/results/tc_scf/saved', .false.) endif call lock_io if(converged) then - write(json_unit, json_true_fmtx) 'converged' + call json_add('/results/tc_scf/converged', .true.) call ezfio_set_tc_scf_converged_tcscf(converged) else - write(json_unit, json_false_fmtx) 'converged' + call json_add('/results/tc_scf/converged', .false.) endif call unlock_io if(qp_stop()) exit enddo - write(json_unit, json_dict_close_fmtx) - ! --- if(converged)then diff --git a/plugins/local/tc_scf/tc_scf.irp.f b/plugins/local/tc_scf/tc_scf.irp.f index e82082e8..d39069ee 100644 --- a/plugins/local/tc_scf/tc_scf.irp.f +++ b/plugins/local/tc_scf/tc_scf.irp.f @@ -49,7 +49,7 @@ subroutine main() print *, ' env_type = ', env_type print *, ' core_tc_op = ',core_tc_op - write(json_unit,json_array_open_fmt) 'tc-scf' + call json_init('tc_scf') call rh_tcscf_diis() @@ -64,8 +64,6 @@ subroutine main() endif call print_energy_and_mos(good_angles) - write(json_unit,json_array_close_fmtx) - call json_close end From 7b603f4d47c1a469afc81c3d1e73d79456cb656b Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Mon, 31 Aug 2026 11:33:02 +0200 Subject: [PATCH 10/26] Restore stable degenerate TC eigenspace rotation (cherry picked from commit e3d98bf548cd12814cdfe1e7518a9c5c75d66fb5) --- plugins/local/non_hermit_dav/biorthog.irp.f | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/local/non_hermit_dav/biorthog.irp.f b/plugins/local/non_hermit_dav/biorthog.irp.f index 271301e5..2c0127b1 100644 --- a/plugins/local/non_hermit_dav/biorthog.irp.f +++ b/plugins/local/non_hermit_dav/biorthog.irp.f @@ -170,8 +170,8 @@ subroutine non_hrmt_bieig_degen(n, A, s_right_in, thr_d, thr_nd, leigvec, reigve enddo enddo ! orthogonalize the right eigenvectors by diagonalizing the S matrix -! call lapack_diagd(seigval,seigvec,sphichi,n_dim,n_dim) - call pivoted_cholesky( sphichi, n_dim, -1.d0, n_dim, seigvec) + call lapack_diagd(seigval,seigvec,sphichi,n_dim,n_dim) + !call pivoted_cholesky( sphichi, n_dim, -1.d0, n_dim, seigvec) ! get the orthogonal eigenvectors in the big basis reigvec_tmp = 0.d0 do j = 1, n_dim From bbcc0af74ae3cbc633e4b46e0159ec88a9230bb3 Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:53:35 +0100 Subject: [PATCH 11/26] Share QMCkl gradient work in bounded grid blocks (cherry picked from commit 4d7bce67eaff9375ba68d118b418dc060274a6f7) --- .../non_h_ints_mu/jast_deriv_utils_vect.irp.f | 107 +++++++++ plugins/local/non_h_ints_mu/tc_integ.irp.f | 203 ++++++++++-------- 2 files changed, 216 insertions(+), 94 deletions(-) diff --git a/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f b/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f index fc70be70..76299adb 100644 --- a/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f +++ b/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f @@ -150,6 +150,113 @@ subroutine get_grad1_u12_withsq_r1_seq(ipoint, n_grid2, resx, resy, resz, res) ! --- +subroutine get_grad1_u12_withsq_qmckl_block(ipoint_first, n_grid1, n_grid2, resx, resy, resz, res) + + BEGIN_DOC + ! QMCkl gradient for a contiguous block of r1 grid points. + ! The shared QMCkl context is updated once, outside OpenMP regions. + END_DOC + + use qmckl + + implicit none + integer, intent(in) :: ipoint_first, n_grid1, n_grid2 + double precision, intent(out) :: resx(n_grid2,n_grid1), resy(n_grid2,n_grid1) + double precision, intent(out) :: resz(n_grid2,n_grid1), res (n_grid2,n_grid1) + + integer :: i_grid1, ipoint, jpoint + integer*8 :: k, n_points + double precision :: dx, dy, dz, fac_en + double precision, allocatable :: rij(:,:,:), gl(:,:,:) + integer(qmckl_exit_code) :: rc + + PROVIDE qmckl_ctx_jastrow + PROVIDE elec_num + PROVIDE final_grid_points final_grid_points_extra + + n_points = int(n_grid1,8) * int(n_grid2,8) + allocate(rij(3,2,n_points), gl(2,4,n_points)) + + k = 0_8 + do i_grid1 = 1, n_grid1 + ipoint = ipoint_first + i_grid1 - 1 + do jpoint = 1, n_grid2 + k = k + 1_8 + rij(1:3,1,k) = final_grid_points (1:3,ipoint) + rij(1:3,2,k) = final_grid_points_extra(1:3,jpoint) + enddo + enddo + + rc = qmckl_set_electron_coord(qmckl_ctx_jastrow, 'N', n_points, rij, 6_8*n_points) + if(rc /= QMCKL_SUCCESS) then + print *, irp_here, 'qmckl error in set_electron_coord' + rc = qmckl_check(qmckl_ctx_jastrow, rc) + stop -1 + endif + + rc = qmckl_get_jastrow_champ_factor_ee_gl(qmckl_ctx_jastrow, gl, 8_8*n_points) + if(rc /= QMCKL_SUCCESS) then + print *, irp_here, 'qmckl error in fact_ee_gl' + rc = qmckl_check(qmckl_ctx_jastrow, rc) + stop -1 + endif + + k = 0_8 + do i_grid1 = 1, n_grid1 + do jpoint = 1, n_grid2 + k = k + 1_8 + resx(jpoint,i_grid1) = gl(1,1,k) + resy(jpoint,i_grid1) = gl(1,2,k) + resz(jpoint,i_grid1) = gl(1,3,k) + enddo + enddo + + rc = qmckl_get_jastrow_champ_factor_een_gl(qmckl_ctx_jastrow, gl, 8_8*n_points) + if(rc /= QMCKL_SUCCESS) then + print *, irp_here, 'qmckl error in fact_een_gl' + rc = qmckl_check(qmckl_ctx_jastrow, rc) + stop -1 + endif + + k = 0_8 + do i_grid1 = 1, n_grid1 + do jpoint = 1, n_grid2 + k = k + 1_8 + resx(jpoint,i_grid1) = resx(jpoint,i_grid1) + gl(1,1,k) + resy(jpoint,i_grid1) = resy(jpoint,i_grid1) + gl(1,2,k) + resz(jpoint,i_grid1) = resz(jpoint,i_grid1) + gl(1,3,k) + enddo + enddo + + rc = qmckl_get_jastrow_champ_factor_en_gl(qmckl_ctx_jastrow, gl, 8_8*n_points) + if(rc /= QMCKL_SUCCESS) then + print *, irp_here, 'qmckl error in fact_en_gl' + rc = qmckl_check(qmckl_ctx_jastrow, rc) + stop -1 + endif + + fac_en = 1.d0 / dble(elec_num - 1) + k = 0_8 + do i_grid1 = 1, n_grid1 + do jpoint = 1, n_grid2 + k = k + 1_8 + dx = resx(jpoint,i_grid1) + fac_en * gl(1,1,k) + dy = resy(jpoint,i_grid1) + fac_en * gl(1,2,k) + dz = resz(jpoint,i_grid1) + fac_en * gl(1,3,k) + resx(jpoint,i_grid1) = dx + resy(jpoint,i_grid1) = dy + resz(jpoint,i_grid1) = dz + res (jpoint,i_grid1) = dx*dx + dy*dy + dz*dz + enddo + enddo + + deallocate(rij, gl) + + return +end + +! --- + subroutine grad1_j12_r1_seq(r1, n_grid2, gradx, grady, gradz) use sizet diff --git a/plugins/local/non_h_ints_mu/tc_integ.irp.f b/plugins/local/non_h_ints_mu/tc_integ.irp.f index abd4c1ed..bcdb6c07 100644 --- a/plugins/local/non_h_ints_mu/tc_integ.irp.f +++ b/plugins/local/non_h_ints_mu/tc_integ.irp.f @@ -1,4 +1,3 @@ -use sizet BEGIN_PROVIDER [double precision, int2_grad1_u12_ao, (ao_num, ao_num, n_points_final_grid, 3)] @@ -11,8 +10,7 @@ END_DOC implicit none - integer :: m - integer(size_t) :: ipoint, i, j, jpoint + integer :: ipoint, i, j, m, jpoint double precision :: time0, time1 double precision :: x, y, z, r2 double precision :: dx, dy, dz @@ -49,15 +47,15 @@ if(tc_save_mem) then - integer(size_t) :: n_blocks, n_rest, n_pass - integer(size_t) :: i_blocks, i_rest, i_pass, ii + integer :: n_blocks, n_rest, n_pass + integer :: i_blocks, i_rest, i_pass, ii double precision :: mem, n_double - double precision, allocatable :: tmp(:,:,:), xx(:) + double precision, allocatable :: tmp(:,:,:), xx(:,:) double precision, allocatable :: tmp_grad1_u12(:,:,:) PROVIDE final_weight_at_r_vector_extra aos_in_r_array_extra - allocate(tmp(n_points_extra_final_grid,ao_num,ao_num), xx(n_points_extra_final_grid)) + allocate(tmp(n_points_extra_final_grid,ao_num,ao_num)) !$OMP PARALLEL & !$OMP DEFAULT (NONE) & !$OMP PRIVATE (j, i, jpoint) & @@ -75,60 +73,69 @@ call total_memory(mem) mem = max(1.d0, qp_max_mem - mem) n_double = mem * 1.d8 - n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), & - 1.d0*n_points_final_grid), size_t) - n_rest = int(mod(n_points_final_grid, n_blocks), size_t) - n_pass = int((n_points_final_grid - n_rest) / n_blocks, size_t) - call write_int(6, int(n_pass, 4), 'Number of passes') - call write_int(6, int(n_blocks, 4), 'Size of the blocks') - call write_int(6, int(n_rest, 4), 'Size of the last block') - allocate(tmp_grad1_u12(n_points_extra_final_grid,n_blocks,3)) + if(j2e_type .eq. "Qmckl") then + ! Four result and fourteen explicit QMCkl scratch doubles per pair. + n_blocks = int(min(n_double / (n_points_extra_final_grid * 18.d0), 1.d0*n_points_final_grid)) + else + n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), 1.d0*n_points_final_grid)) + endif + n_blocks = max(1, n_blocks) + n_rest = int(mod(n_points_final_grid, n_blocks)) + n_pass = int((n_points_final_grid - n_rest) / n_blocks) + call write_int(6, n_pass, 'Number of passes') + call write_int(6, n_blocks, 'Size of the blocks') + call write_int(6, n_rest, 'Size of the last block') + allocate(tmp_grad1_u12(n_points_extra_final_grid,n_blocks,3), xx(n_points_extra_final_grid,n_blocks)) do i_pass = 1, n_pass ii = (i_pass-1)*n_blocks + 1 - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_blocks, ipoint) & - !$OMP SHARED (n_blocks, n_points_extra_final_grid, ii, final_grid_points, xx, tmp_grad1_u12) - !$OMP DO - do i_blocks = 1, n_blocks - ipoint = ii - 1 + i_blocks ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_blocks,1), tmp_grad1_u12(1,i_blocks,2), tmp_grad1_u12(1,i_blocks,3), xx(1)) - enddo - !$OMP END DO - !$OMP END PARALLEL + if(j2e_type .eq. "Qmckl") then + call get_grad1_u12_withsq_qmckl_block(ii, n_blocks, n_points_extra_final_grid, tmp_grad1_u12(1,1,1), tmp_grad1_u12(1,1,2), tmp_grad1_u12(1,1,3), xx(1,1)) + else + !$OMP PARALLEL & + !$OMP DEFAULT (NONE) & + !$OMP PRIVATE (i_blocks, ipoint) & + !$OMP SHARED (n_blocks, n_points_extra_final_grid, ii, final_grid_points, xx, tmp_grad1_u12) + !$OMP DO + do i_blocks = 1, n_blocks + ipoint = ii - 1 + i_blocks ! r1 + call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_blocks,1), tmp_grad1_u12(1,i_blocks,2), tmp_grad1_u12(1,i_blocks,3), xx(1,i_blocks)) + enddo + !$OMP END DO + !$OMP END PARALLEL + endif do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, int(n_blocks, 4) & - , int(n_points_extra_final_grid, 4), 1.d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12(1,1,m), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_ao(1,1,ii,m), ao_num*ao_num) + call dgemm( "T", "N", ao_num*ao_num, n_blocks, n_points_extra_final_grid, 1.d0 & + , tmp(1,1,1), n_points_extra_final_grid, tmp_grad1_u12(1,1,m), n_points_extra_final_grid & + , 0.d0, int2_grad1_u12_ao(1,1,ii,m), ao_num*ao_num) enddo enddo - deallocate(tmp_grad1_u12) + deallocate(tmp_grad1_u12, xx) if(n_rest .gt. 0) then - allocate(tmp_grad1_u12(n_points_extra_final_grid,n_rest,3)) + allocate(tmp_grad1_u12(n_points_extra_final_grid,n_rest,3), xx(n_points_extra_final_grid,n_rest)) ii = n_pass*n_blocks + 1 - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_rest, ipoint) & - !$OMP SHARED (n_rest, n_points_extra_final_grid, ii, final_grid_points, xx, tmp_grad1_u12) - !$OMP DO - do i_rest = 1, n_rest - ipoint = ii - 1 + i_rest ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_rest,1), tmp_grad1_u12(1,i_rest,2), tmp_grad1_u12(1,i_rest,3), xx(1)) - enddo - !$OMP END DO - !$OMP END PARALLEL + if(j2e_type .eq. "Qmckl") then + call get_grad1_u12_withsq_qmckl_block(ii, n_rest, n_points_extra_final_grid, tmp_grad1_u12(1,1,1), tmp_grad1_u12(1,1,2), tmp_grad1_u12(1,1,3), xx(1,1)) + else + !$OMP PARALLEL & + !$OMP DEFAULT (NONE) & + !$OMP PRIVATE (i_rest, ipoint) & + !$OMP SHARED (n_rest, n_points_extra_final_grid, ii, final_grid_points, xx, tmp_grad1_u12) + !$OMP DO + do i_rest = 1, n_rest + ipoint = ii - 1 + i_rest ! r1 + call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_rest,1), tmp_grad1_u12(1,i_rest,2), tmp_grad1_u12(1,i_rest,3), xx(1,i_rest)) + enddo + !$OMP END DO + !$OMP END PARALLEL + endif do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, int(n_rest, 4) & - , int(n_points_extra_final_grid, 4), 1.d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12(1,1,m), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_ao(1,1,ii,m), ao_num*ao_num) + call dgemm( "T", "N", ao_num*ao_num, n_rest, n_points_extra_final_grid, 1.d0 & + , tmp(1,1,1), n_points_extra_final_grid, tmp_grad1_u12(1,1,m), n_points_extra_final_grid & + , 0.d0, int2_grad1_u12_ao(1,1,ii,m), ao_num*ao_num) enddo - deallocate(tmp_grad1_u12) + deallocate(tmp_grad1_u12, xx) endif - deallocate(tmp,xx) + deallocate(tmp) else ! TODO combine 1shot & int2_grad1_u12_ao_num @@ -234,8 +241,7 @@ END_DOC implicit none - integer :: m - integer(size_t) :: ipoint, i, j, jpoint + integer :: ipoint, i, j, m, jpoint double precision :: x, y, z, r2 double precision :: dx, dy, dz, dr2 double precision :: dx1, dy1, dz1, dx2, dy2, dz2, dr12 @@ -265,8 +271,8 @@ if(tc_save_mem) then - integer(size_t) :: n_blocks, n_rest, n_pass - integer(size_t) :: i_blocks, i_rest, i_pass, ii + integer :: n_blocks, n_rest, n_pass + integer :: i_blocks, i_rest, i_pass, ii double precision :: mem, n_double double precision, allocatable :: tmp(:,:,:), xx(:,:,:) double precision, allocatable :: tmp_grad1_u12_squared(:,:) @@ -291,53 +297,62 @@ call total_memory(mem) mem = max(1.d0, qp_max_mem - mem) n_double = mem * 1.d8 - n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), & - 1.d0*n_points_final_grid), size_t) - n_rest = int(mod(n_points_final_grid, n_blocks), size_t) - n_pass = int((n_points_final_grid - n_rest) / n_blocks, size_t) - call write_int(6, int(n_pass, 4), 'Number of passes') - call write_int(6, int(n_blocks, 4), 'Size of the blocks') - call write_int(6, int(n_rest, 4), 'Size of the last block') + if(j2e_type .eq. "Qmckl") then + ! Four result and fourteen explicit QMCkl scratch doubles per pair. + n_blocks = int(min(n_double / (n_points_extra_final_grid * 18.d0), 1.d0*n_points_final_grid)) + else + n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), 1.d0*n_points_final_grid)) + endif + n_blocks = max(1, n_blocks) + n_rest = int(mod(n_points_final_grid, n_blocks)) + n_pass = int((n_points_final_grid - n_rest) / n_blocks) + call write_int(6, n_pass, 'Number of passes') + call write_int(6, n_blocks, 'Size of the blocks') + call write_int(6, n_rest, 'Size of the last block') allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_blocks), xx(n_points_extra_final_grid,n_blocks,3)) do i_pass = 1, n_pass ii = (i_pass-1)*n_blocks + 1 - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_blocks, ipoint) & - !$OMP SHARED (n_blocks, n_points_extra_final_grid, ii, xx, final_grid_points, tmp_grad1_u12_squared) - !$OMP DO - do i_blocks = 1, n_blocks - ipoint = ii - 1 + i_blocks ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, xx(1,i_blocks,1), xx(1,i_blocks,2), xx(1,i_blocks,3), tmp_grad1_u12_squared(1,i_blocks)) - enddo - !$OMP END DO - !$OMP END PARALLEL - call dgemm( "T", "N", ao_num*ao_num, int(n_blocks, 4) & - , int(n_points_extra_final_grid, 4), -0.5d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12_squared(1,1), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_square_ao(1,1,ii), ao_num*ao_num) + if(j2e_type .eq. "Qmckl") then + call get_grad1_u12_withsq_qmckl_block(ii, n_blocks, n_points_extra_final_grid, xx(1,1,1), xx(1,1,2), xx(1,1,3), tmp_grad1_u12_squared(1,1)) + else + !$OMP PARALLEL & + !$OMP DEFAULT (NONE) & + !$OMP PRIVATE (i_blocks, ipoint) & + !$OMP SHARED (n_blocks, n_points_extra_final_grid, ii, xx, final_grid_points, tmp_grad1_u12_squared) + !$OMP DO + do i_blocks = 1, n_blocks + ipoint = ii - 1 + i_blocks ! r1 + call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, xx(1,i_blocks,1), xx(1,i_blocks,2), xx(1,i_blocks,3), tmp_grad1_u12_squared(1,i_blocks)) + enddo + !$OMP END DO + !$OMP END PARALLEL + endif + call dgemm( "T", "N", ao_num*ao_num, n_blocks, n_points_extra_final_grid, -0.5d0 & + , tmp(1,1,1), n_points_extra_final_grid, tmp_grad1_u12_squared(1,1), n_points_extra_final_grid & + , 0.d0, int2_grad1_u12_square_ao(1,1,ii), ao_num*ao_num) enddo deallocate(tmp_grad1_u12_squared, xx) if(n_rest .gt. 0) then ii = n_pass*n_blocks + 1 allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_rest), xx(n_points_extra_final_grid,n_rest,3)) - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_rest, ipoint) & - !$OMP SHARED (n_rest, n_points_extra_final_grid, ii, xx, final_grid_points, tmp_grad1_u12_squared) - !$OMP DO - do i_rest = 1, n_rest - ipoint = ii - 1 + i_rest ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, xx(1,i_rest,1), xx(1,i_rest,2), xx(1,i_rest,3), tmp_grad1_u12_squared(1,i_rest)) - enddo - !$OMP END DO - !$OMP END PARALLEL - call dgemm( "T", "N", ao_num*ao_num, int(n_rest, 4) & - , int(n_points_extra_final_grid, 4), -0.5d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12_squared(1,1), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_square_ao(1,1,ii), ao_num*ao_num) + if(j2e_type .eq. "Qmckl") then + call get_grad1_u12_withsq_qmckl_block(ii, n_rest, n_points_extra_final_grid, xx(1,1,1), xx(1,1,2), xx(1,1,3), tmp_grad1_u12_squared(1,1)) + else + !$OMP PARALLEL & + !$OMP DEFAULT (NONE) & + !$OMP PRIVATE (i_rest, ipoint) & + !$OMP SHARED (n_rest, n_points_extra_final_grid, ii, xx, final_grid_points, tmp_grad1_u12_squared) + !$OMP DO + do i_rest = 1, n_rest + ipoint = ii - 1 + i_rest ! r1 + call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, xx(1,i_rest,1), xx(1,i_rest,2), xx(1,i_rest,3), tmp_grad1_u12_squared(1,i_rest)) + enddo + !$OMP END DO + !$OMP END PARALLEL + endif + call dgemm( "T", "N", ao_num*ao_num, n_rest, n_points_extra_final_grid, -0.5d0 & + , tmp(1,1,1), n_points_extra_final_grid, tmp_grad1_u12_squared(1,1), n_points_extra_final_grid & + , 0.d0, int2_grad1_u12_square_ao(1,1,ii), ao_num*ao_num) deallocate(tmp_grad1_u12_squared, xx) endif deallocate(tmp) From 5d0d46a01675d46c3b9ebac3d5c9a6b71ee32180 Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:53:50 +0100 Subject: [PATCH 12/26] Repair TC-SCF DIIS history with circular buffer (cherry picked from commit 85c67fcbe05fa5d661c1cad9a051bf9167c06719) --- plugins/local/tc_scf/diis_history.f90 | 369 ++++++++++++++++++ .../local/tc_scf/diis_history_qp_test.irp.f | 64 +++ plugins/local/tc_scf/rh_tcscf_diis.irp.f | 360 ++++++----------- plugins/local/tc_scf/tests/build.ninja | 10 + .../local/tc_scf/tests/test_diis_history.f90 | 215 ++++++++++ 5 files changed, 768 insertions(+), 250 deletions(-) create mode 100644 plugins/local/tc_scf/diis_history.f90 create mode 100644 plugins/local/tc_scf/diis_history_qp_test.irp.f create mode 100644 plugins/local/tc_scf/tests/build.ninja create mode 100644 plugins/local/tc_scf/tests/test_diis_history.f90 diff --git a/plugins/local/tc_scf/diis_history.f90 b/plugins/local/tc_scf/diis_history.f90 new file mode 100644 index 00000000..a466f772 --- /dev/null +++ b/plugins/local/tc_scf/diis_history.f90 @@ -0,0 +1,369 @@ +module diis_history_module + + implicit none + private + + integer, parameter, public :: diis_success = 0 + integer, parameter, public :: diis_bad_state = 1 + integer, parameter, public :: diis_bad_shape = 2 + integer, parameter, public :: diis_ill_conditioned = 3 + integer, parameter, public :: diis_lapack_failure = 4 + + type, public :: diis_history + private + integer :: matrix_size = 0 + integer :: capacity = 0 + integer :: count = 0 + integer :: next_slot = 1 + double precision, allocatable :: matrix(:,:,:) + double precision, allocatable :: error(:,:,:) + end type diis_history + + public :: diis_initialize + public :: diis_reset + public :: diis_push + public :: diis_count + public :: diis_next_slot + public :: diis_logical_slots + public :: diis_get_entry + public :: diis_build_gram + public :: diis_solve_coefficients + public :: diis_combine_matrix + public :: diis_extrapolate + + interface + subroutine dgetrf(m, n, a, lda, ipiv, info) + integer, intent(in) :: m, n, lda + double precision, intent(inout) :: a(lda,*) + integer, intent(out) :: ipiv(*), info + end subroutine dgetrf + + subroutine dgecon(norm, n, a, lda, anorm, rcond, work, iwork, info) + character, intent(in) :: norm + integer, intent(in) :: n, lda + double precision, intent(in) :: a(lda,*), anorm + double precision, intent(out) :: rcond, work(*) + integer, intent(out) :: iwork(*), info + end subroutine dgecon + + subroutine dgesv(n, nrhs, a, lda, ipiv, b, ldb, info) + integer, intent(in) :: n, nrhs, lda, ldb + double precision, intent(inout) :: a(lda,*), b(ldb,*) + integer, intent(out) :: ipiv(*), info + end subroutine dgesv + end interface + +contains + + subroutine diis_initialize(history, matrix_size, capacity, info) + + implicit none + + type(diis_history), intent(out) :: history + integer, intent(in) :: matrix_size, capacity + integer, intent(out) :: info + + if((matrix_size < 1) .or. (capacity < 1)) then + info = diis_bad_shape + return + endif + + allocate(history%matrix(matrix_size,matrix_size,capacity)) + allocate(history%error(matrix_size,matrix_size,capacity)) + + history%matrix_size = matrix_size + history%capacity = capacity + history%count = 0 + history%next_slot = 1 + history%matrix = 0.d0 + history%error = 0.d0 + info = diis_success + + end subroutine diis_initialize + + + pure subroutine diis_reset(history) + + implicit none + + type(diis_history), intent(inout) :: history + + history%count = 0 + history%next_slot = 1 + + end subroutine diis_reset + + + pure subroutine diis_push(history, matrix, error, inserted_slot, info) + + implicit none + + type(diis_history), intent(inout) :: history + double precision, intent(in) :: matrix(:,:), error(:,:) + integer, intent(out) :: inserted_slot, info + + inserted_slot = 0 + if(.not. allocated(history%matrix)) then + info = diis_bad_state + return + endif + if( (size(matrix,1) /= history%matrix_size) .or. & + (size(matrix,2) /= history%matrix_size) .or. & + (size(error,1) /= history%matrix_size) .or. & + (size(error,2) /= history%matrix_size) ) then + info = diis_bad_shape + return + endif + + inserted_slot = history%next_slot + history%matrix(:,:,inserted_slot) = matrix(:,:) + history%error(:,:,inserted_slot) = error(:,:) + + history%count = min(history%count + 1, history%capacity) + history%next_slot = modulo(inserted_slot, history%capacity) + 1 + info = diis_success + + end subroutine diis_push + + + pure integer function diis_count(history) + + implicit none + + type(diis_history), intent(in) :: history + + diis_count = history%count + + end function diis_count + + + pure integer function diis_next_slot(history) + + implicit none + + type(diis_history), intent(in) :: history + + diis_next_slot = history%next_slot + + end function diis_next_slot + + + pure function diis_logical_slots(history) result(slots) + + implicit none + + type(diis_history), intent(in) :: history + integer, allocatable :: slots(:) + integer :: i, physical_slot + + allocate(slots(history%count)) + if(history%count == 0) return + + ! next_slot points to the oldest entry once the circular buffer is full. + physical_slot = modulo( history%next_slot - history%count - 1, & + history%capacity ) + 1 + do i = 1, history%count + slots(i) = physical_slot + physical_slot = modulo(physical_slot, history%capacity) + 1 + enddo + + end function diis_logical_slots + + + pure subroutine diis_get_entry(history, logical_index, matrix, error, info) + + implicit none + + type(diis_history), intent(in) :: history + integer, intent(in) :: logical_index + double precision, intent(out) :: matrix(:,:), error(:,:) + integer, intent(out) :: info + integer, allocatable :: slots(:) + integer :: physical_slot + + if( (logical_index < 1) .or. & + (logical_index > history%count) ) then + info = diis_bad_state + return + endif + if( (size(matrix,1) /= history%matrix_size) .or. & + (size(matrix,2) /= history%matrix_size) .or. & + (size(error,1) /= history%matrix_size) .or. & + (size(error,2) /= history%matrix_size) ) then + info = diis_bad_shape + return + endif + + slots = diis_logical_slots(history) + physical_slot = slots(logical_index) + matrix(:,:) = history%matrix(:,:,physical_slot) + error(:,:) = history%error(:,:,physical_slot) + info = diis_success + + end subroutine diis_get_entry + + + pure subroutine diis_build_gram(history, gram, info) + + implicit none + + type(diis_history), intent(in) :: history + double precision, allocatable, intent(out) :: gram(:,:) + integer, intent(out) :: info + integer, allocatable :: slots(:) + integer :: i, j + + if(history%count < 1) then + allocate(gram(0,0)) + info = diis_bad_state + return + endif + + slots = diis_logical_slots(history) + allocate(gram(history%count,history%count)) + do j = 1, history%count + do i = 1, history%count + gram(i,j) = sum( history%error(:,:,slots(i)) * & + history%error(:,:,slots(j)) ) + enddo + enddo + info = diis_success + + end subroutine diis_build_gram + + + subroutine diis_solve_coefficients(gram, coefficients, rcond, info, rcond_min) + + implicit none + + double precision, intent(in) :: gram(:,:) + double precision, allocatable, intent(out) :: coefficients(:) + double precision, intent(out) :: rcond + integer, intent(out) :: info + double precision, intent(in), optional :: rcond_min + double precision, allocatable :: augmented(:,:), factorized(:,:) + double precision, allocatable :: rhs(:), work(:) + integer, allocatable :: ipiv(:), iwork(:) + integer :: i, lapack_info, n, system_size + double precision :: anorm, minimum_rcond + + n = size(gram,1) + allocate(coefficients(n)) + coefficients = 0.d0 + rcond = 0.d0 + + if((n < 1) .or. (size(gram,2) /= n)) then + info = diis_bad_shape + return + endif + + minimum_rcond = 1.d-14 + if(present(rcond_min)) minimum_rcond = rcond_min + + system_size = n + 1 + allocate(augmented(system_size,system_size)) + allocate(factorized(system_size,system_size)) + allocate(rhs(system_size), ipiv(system_size)) + allocate(work(4*system_size), iwork(system_size)) + + augmented = 0.d0 + augmented(1:n,1:n) = gram(:,:) + augmented(1:n,system_size) = -1.d0 + augmented(system_size,1:n) = -1.d0 + rhs = 0.d0 + rhs(system_size) = -1.d0 + + anorm = 0.d0 + do i = 1, system_size + anorm = max(anorm, sum(abs(augmented(:,i)))) + enddo + + factorized(:,:) = augmented(:,:) + call dgetrf( system_size, system_size, factorized, system_size, & + ipiv, lapack_info ) + if(lapack_info /= 0) then + info = diis_lapack_failure + return + endif + + call dgecon( '1', system_size, factorized, system_size, anorm, & + rcond, work, iwork, lapack_info ) + if(lapack_info /= 0) then + info = diis_lapack_failure + return + endif + if(rcond < minimum_rcond) then + info = diis_ill_conditioned + return + endif + + call dgesv( system_size, 1, augmented, system_size, ipiv, rhs, & + system_size, lapack_info ) + if(lapack_info /= 0) then + info = diis_lapack_failure + return + endif + + coefficients(:) = rhs(1:n) + info = diis_success + + end subroutine diis_solve_coefficients + + + pure subroutine diis_combine_matrix(history, coefficients, matrix, info) + + implicit none + + type(diis_history), intent(in) :: history + double precision, intent(in) :: coefficients(:) + double precision, intent(out) :: matrix(:,:) + integer, intent(out) :: info + integer, allocatable :: slots(:) + integer :: i + + if( (size(coefficients) /= history%count) .or. & + (size(matrix,1) /= history%matrix_size) .or. & + (size(matrix,2) /= history%matrix_size) ) then + info = diis_bad_shape + return + endif + + slots = diis_logical_slots(history) + matrix = 0.d0 + do i = 1, history%count + matrix(:,:) = matrix(:,:) + coefficients(i) * & + history%matrix(:,:,slots(i)) + enddo + info = diis_success + + end subroutine diis_combine_matrix + + + subroutine diis_extrapolate(history, matrix, coefficients, rcond, info, rcond_min) + + implicit none + + type(diis_history), intent(in) :: history + double precision, intent(out) :: matrix(:,:) + double precision, allocatable, intent(out) :: coefficients(:) + double precision, intent(out) :: rcond + integer, intent(out) :: info + double precision, intent(in), optional :: rcond_min + double precision, allocatable :: gram(:,:) + + call diis_build_gram(history, gram, info) + if(info /= diis_success) return + + if(present(rcond_min)) then + call diis_solve_coefficients( gram, coefficients, rcond, & + info, rcond_min ) + else + call diis_solve_coefficients( gram, coefficients, rcond, info ) + endif + if(info /= diis_success) return + + call diis_combine_matrix(history, coefficients, matrix, info) + + end subroutine diis_extrapolate + +end module diis_history_module diff --git a/plugins/local/tc_scf/diis_history_qp_test.irp.f b/plugins/local/tc_scf/diis_history_qp_test.irp.f new file mode 100644 index 00000000..4edf2ff4 --- /dev/null +++ b/plugins/local/tc_scf/diis_history_qp_test.irp.f @@ -0,0 +1,64 @@ +! --- + +program diis_history_qp_test + + use diis_history_module + + implicit none + + type(diis_history) :: history + double precision :: fock(2,2), error(2,2) + integer :: expected, info, inserted_slot, iteration + + call diis_initialize(history, 2, 3, info) + if(info /= diis_success) then + stop 'QP DIIS test: initialization failed' + endif + + do iteration = 1, 5 + fock(:,:) = dble(iteration) + error(:,:) = -dble(iteration) + call diis_push(history, fock, error, inserted_slot, info) + if(info /= diis_success) then + stop 'QP DIIS test: insertion failed' + endif + expected = modulo(iteration - 1, 3) + 1 + if(inserted_slot /= expected) then + stop 'QP DIIS test: wrong physical insertion slot' + endif + enddo + + if(diis_count(history) /= 3) then + stop 'QP DIIS test: wrong count after wraparound' + endif + if(diis_next_slot(history) /= 3) then + stop 'QP DIIS test: wrong next slot after wraparound' + endif + + do iteration = 1, 3 + call diis_get_entry(history, iteration, fock, error, info) + if(info /= diis_success) then + stop 'QP DIIS test: logical retrieval failed' + endif + expected = iteration + 2 + if(fock(1,1) /= dble(expected)) then + stop 'QP DIIS test: wrong logical Fock chronology' + endif + if(error(1,1) /= -dble(expected)) then + stop 'QP DIIS test: Fock/error pair separated' + endif + enddo + + call diis_reset(history) + if(diis_count(history) /= 0) then + stop 'QP DIIS test: reset did not clear logical history' + endif + if(diis_next_slot(history) /= 1) then + stop 'QP DIIS test: reset did not restore first slot' + endif + + print *, 'PASS: QP/IRPF90 TC-SCF DIIS history integration test' + +end + +! --- diff --git a/plugins/local/tc_scf/rh_tcscf_diis.irp.f b/plugins/local/tc_scf/rh_tcscf_diis.irp.f index 66b5d4e6..8555a1f0 100644 --- a/plugins/local/tc_scf/rh_tcscf_diis.irp.f +++ b/plugins/local/tc_scf/rh_tcscf_diis.irp.f @@ -1,50 +1,50 @@ ! --- -! TODO -! level shift of SCF is well adapted -! for 0.5 x F -! - subroutine rh_tcscf_diis() - use qp_json, only: json_add - implicit none + use diis_history_module - integer :: i, j, it - integer :: dim_DIIS, index_dim_DIIS - logical :: converged - double precision :: etc_tot, etc_1e, etc_2e, etc_3e, e_save, e_delta - double precision :: tc_grad, g_save, g_delta, g_delta_th - double precision :: level_shift_save, rate_th - double precision :: t0, t1 - double precision :: er_DIIS, er_delta, er_save, er_delta_th - double precision, allocatable :: F_DIIS(:,:,:), E_DIIS(:,:,:) - double precision, allocatable :: mo_r_coef_save(:,:), mo_l_coef_save(:,:) + implicit none - logical, external :: qp_stop + type(diis_history) :: history + integer :: info, inserted_slot, it + integer :: history_count + logical :: converged + double precision :: etc_tot, etc_1e, etc_2e, etc_3e + double precision :: e_save, e_delta + double precision :: level_shift_save, rate_th + double precision :: t0, t1 + double precision :: er_DIIS, er_delta, er_save + double precision :: rcond + double precision, allocatable :: coefficients(:) + double precision, allocatable :: fock_before_diis(:,:) + double precision, allocatable :: fock_extrapolated(:,:) + double precision, allocatable :: mo_r_coef_save(:,:) + double precision, allocatable :: mo_l_coef_save(:,:) + + logical, external :: qp_stop PROVIDE level_shift_TCSCF PROVIDE mo_l_coef mo_r_coef - it = 0 - e_save = 0.d0 - dim_DIIS = 0 - g_delta_th = 1d0 - er_delta_th = 1d0 - rate_th = 0.1d0 + it = 0 + e_save = 0.d0 + rate_th = 0.1d0 - allocate(mo_r_coef_save(ao_num,mo_num), mo_l_coef_save(ao_num,mo_num)) + allocate(mo_r_coef_save(ao_num,mo_num)) + allocate(mo_l_coef_save(ao_num,mo_num)) + allocate(fock_before_diis(ao_num,ao_num)) + allocate(fock_extrapolated(ao_num,ao_num)) mo_l_coef_save = 0.d0 mo_r_coef_save = 0.d0 - allocate(F_DIIS(ao_num,ao_num,max_dim_DIIS_TCSCF), E_DIIS(ao_num,ao_num,max_dim_DIIS_TCSCF)) - F_DIIS = 0.d0 - E_DIIS = 0.d0 + call diis_initialize(history, ao_num, max_dim_DIIS_TCSCF, info) + if(info /= diis_success) then + stop 'TC-SCF DIIS history initialization failed' + endif call write_time(6) - ! --- - write(6, '(A4,1X, A16,1X, A16,1X, A16,1X, A16,1X, A16,1X, A16,1X, A16,1X, A4, 1X, A8)') & '====', '================', '================', '================', '================', '================' & , '================', '================', '====', '========' @@ -55,36 +55,29 @@ subroutine rh_tcscf_diis() '====', '================', '================', '================', '================', '================' & , '================', '================', '====', '========' - - ! first iteration (HF orbitals) call wall_time(t0) etc_tot = TC_HF_energy etc_1e = TC_HF_one_e_energy etc_2e = TC_HF_two_e_energy etc_3e = TC_HF_three_e_energy - !tc_grad = grad_non_hermit er_DIIS = maxval(abs(FQS_SQF_mo)) e_delta = dabs(etc_tot - e_save) e_save = etc_tot - !g_save = tc_grad er_save = er_DIIS + history_count = diis_count(history) call wall_time(t1) write(6, '(I4,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, I4,1X, F8.2)') & - it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, er_DIIS, level_shift_tcscf, dim_DIIS, (t1-t0)/60.d0 - - ! --- + it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, er_DIIS, level_shift_tcscf, history_count, (t1-t0)/60.d0 PROVIDE FQS_SQF_ao Fock_matrix_tc_ao_tot converged = .false. call ezfio_set_tc_scf_converged_tcscf(converged) - !do while((tc_grad .gt. dsqrt(thresh_tcscf)) .and. (er_DIIS .gt. dsqrt(thresh_tcscf))) do while(.not. converged) -! call print_angles_tc() call wall_time(t0) it += 1 @@ -93,58 +86,59 @@ subroutine rh_tcscf_diis() exit endif - dim_DIIS = min(dim_DIIS+1, max_dim_DIIS_TCSCF) - - ! --- + ! This snapshot is independent of whether the current pair is inserted. + fock_before_diis(:,:) = Fock_matrix_tc_ao_tot(:,:) + inserted_slot = 0 + rcond = 0.d0 if(dabs(e_delta) > 1.d-12) then + call diis_push( history, Fock_matrix_tc_ao_tot, FQS_SQF_ao, & + inserted_slot, info ) + if(info /= diis_success) then + stop 'TC-SCF DIIS history insertion failed' + endif - index_dim_DIIS = mod(dim_DIIS-1, max_dim_DIIS_TCSCF) + 1 - do j = 1, ao_num - do i = 1, ao_num - F_DIIS(i,j,index_dim_DIIS) = Fock_matrix_tc_ao_tot(i,j) - E_DIIS(i,j,index_dim_DIIS) = FQS_SQF_ao (i,j) - enddo - enddo - - call extrapolate_TC_Fock_matrix(E_DIIS, F_DIIS, Fock_matrix_tc_ao_tot, size(Fock_matrix_tc_ao_tot, 1), it, dim_DIIS) - - call ao_to_mo_bi_ortho( Fock_matrix_tc_ao_tot, size(Fock_matrix_tc_ao_tot, 1) & - , Fock_matrix_tc_mo_tot, size(Fock_matrix_tc_mo_tot, 1) ) - TOUCH Fock_matrix_tc_mo_tot fock_matrix_tc_diag_mo_tot + call diis_extrapolate( history, fock_extrapolated, & + coefficients, rcond, info ) + if(info == diis_success) then + Fock_matrix_tc_ao_tot(:,:) = fock_extrapolated(:,:) + call ao_to_mo_bi_ortho( Fock_matrix_tc_ao_tot, & + size(Fock_matrix_tc_ao_tot, 1), & + Fock_matrix_tc_mo_tot, & + size(Fock_matrix_tc_mo_tot, 1) ) + TOUCH Fock_matrix_tc_mo_tot fock_matrix_tc_diag_mo_tot + else + ! A rejected solve keeps the unextrapolated Fock and starts fresh. + call diis_reset(history) + print *, ' TC-DIIS history reset after rejected solve, info = ', info + print *, ' TC-DIIS reciprocal condition estimate = ', rcond + endif endif - ! --- - - mo_l_coef(1:ao_num,1:mo_num) = fock_tc_leigvec_ao(1:ao_num,1:mo_num) - mo_r_coef(1:ao_num,1:mo_num) = fock_tc_reigvec_ao(1:ao_num,1:mo_num) - !call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) - !call ezfio_set_bi_ortho_mos_mo_r_coef(mo_r_coef) + mo_l_coef(1:ao_num,1:mo_num) = & + fock_tc_leigvec_ao(1:ao_num,1:mo_num) + mo_r_coef(1:ao_num,1:mo_num) = & + fock_tc_reigvec_ao(1:ao_num,1:mo_num) TOUCH mo_l_coef mo_r_coef - ! --- - - !g_delta = grad_non_hermit - g_save er_delta = maxval(abs(FQS_SQF_mo)) - er_save if((er_delta > rate_th * er_save) .and. (it > 1)) then - - Fock_matrix_tc_ao_tot(1:ao_num,1:ao_num) = F_DIIS(1:ao_num,1:ao_num,index_dim_DIIS) - call ao_to_mo_bi_ortho( Fock_matrix_tc_ao_tot, size(Fock_matrix_tc_ao_tot, 1) & - , Fock_matrix_tc_mo_tot, size(Fock_matrix_tc_mo_tot, 1) ) + Fock_matrix_tc_ao_tot(1:ao_num,1:ao_num) = & + fock_before_diis(1:ao_num,1:ao_num) + call ao_to_mo_bi_ortho( Fock_matrix_tc_ao_tot, & + size(Fock_matrix_tc_ao_tot, 1), & + Fock_matrix_tc_mo_tot, & + size(Fock_matrix_tc_mo_tot, 1) ) TOUCH Fock_matrix_tc_mo_tot fock_matrix_tc_diag_mo_tot - mo_l_coef(1:ao_num,1:mo_num) = fock_tc_leigvec_ao(1:ao_num,1:mo_num) - mo_r_coef(1:ao_num,1:mo_num) = fock_tc_reigvec_ao(1:ao_num,1:mo_num) - !call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) - !call ezfio_set_bi_ortho_mos_mo_r_coef(mo_r_coef) + mo_l_coef(1:ao_num,1:mo_num) = & + fock_tc_leigvec_ao(1:ao_num,1:mo_num) + mo_r_coef(1:ao_num,1:mo_num) = & + fock_tc_reigvec_ao(1:ao_num,1:mo_num) TOUCH mo_l_coef mo_r_coef - endif - ! --- - - !g_delta = grad_non_hermit - g_save er_delta = maxval(abs(FQS_SQF_mo)) - er_save mo_l_coef_save(1:ao_num,1:mo_num) = mo_l_coef(1:ao_num,1:mo_num) @@ -152,25 +146,25 @@ subroutine rh_tcscf_diis() do while((er_delta > rate_th * er_save) .and. (it > 1)) print *, ' big or bad step ' - !print *, g_delta , rate_th * g_save print *, er_delta, rate_th * er_save - mo_l_coef(1:ao_num,1:mo_num) = mo_l_coef_save(1:ao_num,1:mo_num) - mo_r_coef(1:ao_num,1:mo_num) = mo_r_coef_save(1:ao_num,1:mo_num) + mo_l_coef(1:ao_num,1:mo_num) = & + mo_l_coef_save(1:ao_num,1:mo_num) + mo_r_coef(1:ao_num,1:mo_num) = & + mo_r_coef_save(1:ao_num,1:mo_num) if(level_shift_TCSCF <= .1d0) then level_shift_TCSCF = 1.d0 else - level_shift_TCSCF = level_shift_TCSCF * 3.0d0 + level_shift_TCSCF = level_shift_TCSCF * 3.d0 endif TOUCH mo_l_coef mo_r_coef level_shift_TCSCF - mo_l_coef(1:ao_num,1:mo_num) = fock_tc_leigvec_ao(1:ao_num,1:mo_num) - mo_r_coef(1:ao_num,1:mo_num) = fock_tc_reigvec_ao(1:ao_num,1:mo_num) - !call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) - !call ezfio_set_bi_ortho_mos_mo_r_coef(mo_r_coef) + mo_l_coef(1:ao_num,1:mo_num) = & + fock_tc_leigvec_ao(1:ao_num,1:mo_num) + mo_r_coef(1:ao_num,1:mo_num) = & + fock_tc_reigvec_ao(1:ao_num,1:mo_num) TOUCH mo_l_coef mo_r_coef - !g_delta = grad_non_hermit - g_save er_delta = maxval(abs(FQS_SQF_mo)) - er_save if(level_shift_TCSCF - level_shift_save > 40.d0) then @@ -179,11 +173,9 @@ subroutine rh_tcscf_diis() exit endif - dim_DIIS = 0 + call diis_reset(history) enddo - ! --- - level_shift_TCSCF = level_shift_TCSCF * 0.5d0 SOFT_TOUCH level_shift_TCSCF @@ -191,75 +183,70 @@ subroutine rh_tcscf_diis() etc_1e = TC_HF_one_e_energy etc_2e = TC_HF_two_e_energy etc_3e = TC_HF_three_e_energy - !tc_grad = grad_non_hermit - er_DIIS = maxval(abs(FQS_SQF_mo)) - e_delta = dabs(etc_tot - e_save) - !g_delta = tc_grad - g_save + er_DIIS = maxval(abs(FQS_SQF_mo)) + e_delta = dabs(etc_tot - e_save) er_delta = er_DIIS - er_save - + e_save = etc_tot - !g_save = tc_grad level_shift_save = level_shift_TCSCF er_save = er_DIIS - !g_delta_th = dabs(tc_grad) ! g_delta) - er_delta_th = dabs(er_DIIS) !er_delta) - converged = er_DIIS .lt. dsqrt(thresh_tcscf) + history_count = diis_count(history) call wall_time(t1) - !write(6, '(I4,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, I4,1X, F8.2)') & - ! it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, tc_grad, er_DIIS, level_shift_tcscf, dim_DIIS, (t1-t0)/60.d0 write(6, '(I4,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, I4,1X, F8.2)') & - it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, er_DIIS, level_shift_tcscf, dim_DIIS, (t1-t0)/60.d0 - - -! Write data in JSON file + it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, er_DIIS, level_shift_tcscf, history_count, (t1-t0)/60.d0 call lock_io - call json_add('/results/tc_scf/iteration', it) - call json_add('/results/tc_scf/scf_tc_energy', etc_tot) - call json_add('/results/tc_scf/energy_1e', etc_1e) - call json_add('/results/tc_scf/energy_2e', etc_2e) - call json_add('/results/tc_scf/energy_3e', etc_3e) - call json_add('/results/tc_scf/delta_energy', e_delta) - call json_add('/results/tc_scf/diis_error', er_DIIS) - call json_add('/results/tc_scf/level_shift', level_shift_tcscf) - call json_add('/results/tc_scf/diis_size', dim_DIIS) - call json_add('/results/tc_scf/wall_time_min', (t1-t0)/60.d0) + if(it == 1) then + write(json_unit, json_dict_uopen_fmt) + else + write(json_unit, json_dict_close_uopen_fmt) + endif + write(json_unit, json_int_fmt) ' iteration ', it + write(json_unit, json_real_fmt) ' SCF TC Energy ', etc_tot + write(json_unit, json_real_fmt) ' E(1e) ', etc_1e + write(json_unit, json_real_fmt) ' E(2e) ', etc_2e + write(json_unit, json_real_fmt) ' E(3e) ', etc_3e + write(json_unit, json_real_fmt) ' delta Energy ', e_delta + write(json_unit, json_real_fmt) ' DIIS error ', er_DIIS + write(json_unit, json_real_fmt) ' level_shift ', level_shift_tcscf + write(json_unit, json_int_fmtx) ' DIIS ', history_count + write(json_unit, json_real_fmt) ' Wall time (min)', (t1-t0)/60.d0 call unlock_io if(er_delta .lt. 0.d0) then call ezfio_set_tc_scf_tcscf_energy(etc_tot) call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) call ezfio_set_bi_ortho_mos_mo_r_coef(mo_r_coef) - call json_add('/results/tc_scf/saved', .true.) + write(json_unit, json_true_fmt) 'saved' else - call json_add('/results/tc_scf/saved', .false.) + write(json_unit, json_false_fmt) 'saved' endif call lock_io if(converged) then - call json_add('/results/tc_scf/converged', .true.) + write(json_unit, json_true_fmtx) 'converged' call ezfio_set_tc_scf_converged_tcscf(converged) else - call json_add('/results/tc_scf/converged', .false.) + write(json_unit, json_false_fmtx) 'converged' endif call unlock_io if(qp_stop()) exit enddo - ! --- + write(json_unit, json_dict_close_fmtx) - if(converged)then - print *, ' TCSCF DIIS converged !' + if(converged) then + print *, ' TCSCF DIIS converged !' else - print*,'Warning, TCSCF DIIS did not converge ...' + print *, 'Warning, TCSCF DIIS did not converge ...' endif - !call print_energy_and_mos(good_angles) call write_time(6) - deallocate(mo_r_coef_save, mo_l_coef_save, F_DIIS, E_DIIS) + deallocate(mo_r_coef_save, mo_l_coef_save) + deallocate(fock_before_diis, fock_extrapolated) call ezfio_set_tc_scf_tcscf_energy(TC_HF_energy) call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) @@ -269,130 +256,3 @@ subroutine rh_tcscf_diis() ! --- -subroutine extrapolate_TC_Fock_matrix(E_DIIS, F_DIIS, F_ao, size_F_ao, it, dim_DIIS) - - BEGIN_DOC - ! - ! Compute the extrapolated Fock matrix using the DIIS procedure - ! - ! e = \sum_i c_i e_i and \sum_i c_i = 1 - ! ==> lagrange multiplier with L = |e|^2 - \lambda (\sum_i c_i = 1) - ! - END_DOC - - implicit none - - integer, intent(in) :: it, size_F_ao - integer, intent(inout) :: dim_DIIS - double precision, intent(in) :: F_DIIS(ao_num,ao_num,dim_DIIS) - double precision, intent(in) :: E_DIIS(ao_num,ao_num,dim_DIIS) - double precision, intent(inout) :: F_ao(size_F_ao,ao_num) - - double precision, allocatable :: B_matrix_DIIS(:,:), X_vector_DIIS(:), C_vector_DIIS(:) - - integer :: i, j, k, l, i_DIIS, j_DIIS - integer :: lwork - double precision :: rcond, ferr, berr - integer, allocatable :: iwork(:) - double precision, allocatable :: scratch(:,:) - - if(dim_DIIS < 1) then - return - endif - - allocate( B_matrix_DIIS(dim_DIIS+1,dim_DIIS+1), X_vector_DIIS(dim_DIIS+1) & - , C_vector_DIIS(dim_DIIS+1), scratch(ao_num,ao_num) ) - - ! Compute the matrices B and X - B_matrix_DIIS(:,:) = 0.d0 - do j = 1, dim_DIIS - j_DIIS = min(dim_DIIS, mod(it-j, max_dim_DIIS_TCSCF)+1) - - do i = 1, dim_DIIS - i_DIIS = min(dim_DIIS, mod(it-i, max_dim_DIIS_TCSCF)+1) - - ! Compute product of two errors vectors - do l = 1, ao_num - do k = 1, ao_num - B_matrix_DIIS(i,j) = B_matrix_DIIS(i,j) + E_DIIS(k,l,i_DIIS) * E_DIIS(k,l,j_DIIS) - enddo - enddo - - enddo - enddo - - ! Pad B matrix and build the X matrix - - C_vector_DIIS(:) = 0.d0 - do i = 1, dim_DIIS - B_matrix_DIIS(i,dim_DIIS+1) = -1.d0 - B_matrix_DIIS(dim_DIIS+1,i) = -1.d0 - enddo - C_vector_DIIS(dim_DIIS+1) = -1.d0 - - deallocate(scratch) - - ! Estimate condition number of B - integer :: info - double precision :: anorm - integer, allocatable :: ipiv(:) - double precision, allocatable :: AF(:,:) - double precision, external :: dlange - - lwork = max((dim_DIIS+1)**2, (dim_DIIS+1)*5) - allocate(AF(dim_DIIS+1,dim_DIIS+1)) - allocate(ipiv(2*(dim_DIIS+1)), iwork(2*(dim_DIIS+1)) ) - allocate(scratch(lwork,1)) - scratch(:,1) = 0.d0 - - anorm = dlange('1', dim_DIIS+1, dim_DIIS+1, B_matrix_DIIS, size(B_matrix_DIIS, 1), scratch(1,1)) - - AF(:,:) = B_matrix_DIIS(:,:) - call dgetrf(dim_DIIS+1, dim_DIIS+1, AF, size(AF, 1), ipiv, info) - if(info /= 0) then - dim_DIIS = 0 - return - endif - - call dgecon('1', dim_DIIS+1, AF, size(AF, 1), anorm, rcond, scratch, iwork, info) - if(info /= 0) then - dim_DIIS = 0 - return - endif - - if(rcond < 1.d-14) then - dim_DIIS = 0 - return - endif - - ! solve the linear system C = B x X - - X_vector_DIIS = C_vector_DIIS - call dgesv(dim_DIIS+1, 1, B_matrix_DIIS, size(B_matrix_DIIS, 1), ipiv , X_vector_DIIS, size(X_vector_DIIS, 1), info) - - deallocate(scratch, AF, iwork) - if(info < 0) then - stop ' bug in TC-DIIS' - endif - - ! Compute extrapolated Fock matrix - - !$OMP PARALLEL DO PRIVATE(i,j,k) DEFAULT(SHARED) if (ao_num > 200) - do j = 1, ao_num - do i = 1, ao_num - F_ao(i,j) = 0.d0 - enddo - do k = 1, dim_DIIS - if(dabs(X_vector_DIIS(k)) < 1.d-10) cycle - do i = 1,ao_num - ! FPE here - F_ao(i,j) = F_ao(i,j) + X_vector_DIIS(k) * F_DIIS(i,j,dim_DIIS-k+1) - enddo - enddo - enddo - !$OMP END PARALLEL DO - -end - -! --- - diff --git a/plugins/local/tc_scf/tests/build.ninja b/plugins/local/tc_scf/tests/build.ninja new file mode 100644 index 00000000..fb807f6c --- /dev/null +++ b/plugins/local/tc_scf/tests/build.ninja @@ -0,0 +1,10 @@ +rule compile_history + command = gfortran -O0 -g -fcheck=all -Wall -Wextra -J. -c $in -o $out + +rule link_test + command = gfortran -O0 -g -fcheck=all -Wall -Wextra -I. $in -llapack -lblas -o $out + +build diis_history.o: compile_history ../diis_history.f90 +build test_diis_history: link_test diis_history.o test_diis_history.f90 + +default test_diis_history diff --git a/plugins/local/tc_scf/tests/test_diis_history.f90 b/plugins/local/tc_scf/tests/test_diis_history.f90 new file mode 100644 index 00000000..b7a00f6b --- /dev/null +++ b/plugins/local/tc_scf/tests/test_diis_history.f90 @@ -0,0 +1,215 @@ +program test_diis_history + + use diis_history_module + + implicit none + + call test_wraparound_and_pairing() + call test_reset_and_skipped_insertion() + call test_gram_and_extrapolation() + call test_ill_conditioned_rejection() + + print *, 'PASS: diis_history regression tests' + +contains + + subroutine assert_true(condition, message) + + implicit none + + logical, intent(in) :: condition + character(*), intent(in) :: message + + if(.not. condition) then + print *, 'FAIL: ', trim(message) + error stop 1 + endif + + end subroutine assert_true + + + subroutine assert_close(actual, expected, tolerance, message) + + implicit none + + double precision, intent(in) :: actual, expected, tolerance + character(*), intent(in) :: message + + call assert_true( abs(actual - expected) <= tolerance, & + trim(message) ) + + end subroutine assert_close + + + subroutine push_label(history, label) + + implicit none + + type(diis_history), intent(inout) :: history + integer, intent(in) :: label + double precision :: fock(2,2), error(2,2) + integer :: info, inserted_slot + + fock = dble(label) + error = -dble(label) + call diis_push(history, fock, error, inserted_slot, info) + call assert_true(info == diis_success, 'push_label failed') + + end subroutine push_label + + + subroutine assert_history_labels(history, expected, message) + + implicit none + + type(diis_history), intent(in) :: history + integer, intent(in) :: expected(:) + character(*), intent(in) :: message + double precision :: fock(2,2), error(2,2) + integer :: i, info + + call assert_true( diis_count(history) == size(expected), & + trim(message)//': wrong count' ) + do i = 1, size(expected) + call diis_get_entry(history, i, fock, error, info) + call assert_true(info == diis_success, & + trim(message)//': get_entry failed') + call assert_close(fock(1,1), dble(expected(i)), 0.d0, & + trim(message)//': wrong Fock chronology') + call assert_close(error(1,1), -dble(expected(i)), 0.d0, & + trim(message)//': Fock/error pair separated') + enddo + + end subroutine assert_history_labels + + + subroutine test_wraparound_and_pairing() + + implicit none + + type(diis_history) :: history + integer :: info, iteration + + call diis_initialize(history, 2, 4, info) + call assert_true(info == diis_success, 'initialization failed') + + do iteration = 1, 4 + call push_label(history, iteration) + enddo + call assert_history_labels(history, [1, 2, 3, 4], & + 'history before wraparound') + call assert_true(diis_next_slot(history) == 1, & + 'next slot before wraparound') + + call push_label(history, 5) + call assert_history_labels(history, [2, 3, 4, 5], & + 'iteration 5 must evict iteration 1') + call assert_true(diis_next_slot(history) == 2, & + 'next slot after first wraparound') + + do iteration = 6, 8 + call push_label(history, iteration) + enddo + call assert_history_labels(history, [5, 6, 7, 8], & + 'history after full wraparound') + + end subroutine test_wraparound_and_pairing + + + subroutine test_reset_and_skipped_insertion() + + implicit none + + type(diis_history) :: history + integer :: info + + call diis_initialize(history, 2, 4, info) + call push_label(history, 17) + call push_label(history, 18) + call diis_reset(history) + call assert_true(diis_count(history) == 0, 'reset count') + call assert_true(diis_next_slot(history) == 1, 'reset next slot') + + call push_label(history, 19) + call push_label(history, 20) + call assert_history_labels(history, [19, 20], & + 'fresh chronology after reset') + + ! A skipped insertion is represented by not calling diis_push. + call assert_history_labels(history, [19, 20], & + 'skipped insertion must not change history') + + end subroutine test_reset_and_skipped_insertion + + + subroutine test_gram_and_extrapolation() + + implicit none + + type(diis_history) :: history + double precision :: fock(2,2), error(2,2), extrapolated(2,2) + double precision, allocatable :: gram(:,:), coefficients(:) + double precision :: rcond + integer :: info, inserted_slot + + call diis_initialize(history, 2, 2, info) + + ! Fill slot 1 with a stale pair. The two useful entries below then occupy + ! physical slots 2 and 1, so extrapolation must follow logical chronology. + fock = -999.d0 + error = -999.d0 + call diis_push(history, fock, error, inserted_slot, info) + + fock = 0.d0 + fock(1,1) = 10.d0 + fock(2,2) = 10.d0 + error = 0.d0 + error(1,1) = 1.d0 + call diis_push(history, fock, error, inserted_slot, info) + + fock = 0.d0 + fock(1,1) = 20.d0 + fock(2,2) = 20.d0 + error = 0.d0 + error(2,2) = 2.d0 + call diis_push(history, fock, error, inserted_slot, info) + + call diis_build_gram(history, gram, info) + call assert_true(info == diis_success, 'Gram construction failed') + call assert_close(gram(1,1), 1.d0, 1.d-14, 'Gram(1,1)') + call assert_close(gram(1,2), 0.d0, 1.d-14, 'Gram(1,2)') + call assert_close(gram(2,1), 0.d0, 1.d-14, 'Gram(2,1)') + call assert_close(gram(2,2), 4.d0, 1.d-14, 'Gram(2,2)') + + call diis_extrapolate( history, extrapolated, coefficients, & + rcond, info ) + call assert_true(info == diis_success, 'extrapolation failed') + call assert_close(coefficients(1), 0.8d0, 1.d-13, 'coefficient 1') + call assert_close(coefficients(2), 0.2d0, 1.d-13, 'coefficient 2') + call assert_close(sum(coefficients), 1.d0, 1.d-13, & + 'coefficient sum') + call assert_close(extrapolated(1,1), 12.d0, 1.d-12, & + 'extrapolated Fock(1,1)') + call assert_close(extrapolated(2,2), 12.d0, 1.d-12, & + 'extrapolated Fock(2,2)') + + end subroutine test_gram_and_extrapolation + + + subroutine test_ill_conditioned_rejection() + + implicit none + + double precision :: gram(2,2), rcond + double precision, allocatable :: coefficients(:) + integer :: info + + gram = 1.d0 + call diis_solve_coefficients(gram, coefficients, rcond, info) + call assert_true( info == diis_lapack_failure .or. & + info == diis_ill_conditioned, & + 'singular DIIS system must be rejected' ) + + end subroutine test_ill_conditioned_rejection + +end program test_diis_history From 3844b32b8552c530f2f57ad6eb68f3d95e8a872f Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:02:20 +0100 Subject: [PATCH 13/26] Repair TC-SCF level-shift retries (cherry picked from commit de40841fd10993daf66a2711fc66328102abeba9) --- plugins/local/tc_scf/rh_tcscf_diis.irp.f | 63 +++++++++++++++++++----- 1 file changed, 51 insertions(+), 12 deletions(-) diff --git a/plugins/local/tc_scf/rh_tcscf_diis.irp.f b/plugins/local/tc_scf/rh_tcscf_diis.irp.f index 8555a1f0..175190fc 100644 --- a/plugins/local/tc_scf/rh_tcscf_diis.irp.f +++ b/plugins/local/tc_scf/rh_tcscf_diis.irp.f @@ -9,18 +9,23 @@ subroutine rh_tcscf_diis() type(diis_history) :: history integer :: info, inserted_slot, it integer :: history_count + integer, parameter :: max_level_shift_tries = 5 + integer :: n_retry logical :: converged double precision :: etc_tot, etc_1e, etc_2e, etc_3e double precision :: e_save, e_delta double precision :: level_shift_save, rate_th double precision :: t0, t1 double precision :: er_DIIS, er_delta, er_save + double precision :: best_residual, trial_residual double precision :: rcond double precision, allocatable :: coefficients(:) double precision, allocatable :: fock_before_diis(:,:) double precision, allocatable :: fock_extrapolated(:,:) double precision, allocatable :: mo_r_coef_save(:,:) double precision, allocatable :: mo_l_coef_save(:,:) + double precision, allocatable :: mo_r_coef_best(:,:) + double precision, allocatable :: mo_l_coef_best(:,:) logical, external :: qp_stop @@ -33,6 +38,8 @@ subroutine rh_tcscf_diis() allocate(mo_r_coef_save(ao_num,mo_num)) allocate(mo_l_coef_save(ao_num,mo_num)) + allocate(mo_r_coef_best(ao_num,mo_num)) + allocate(mo_l_coef_best(ao_num,mo_num)) allocate(fock_before_diis(ao_num,ao_num)) allocate(fock_extrapolated(ao_num,ao_num)) mo_l_coef_save = 0.d0 @@ -88,6 +95,10 @@ subroutine rh_tcscf_diis() ! This snapshot is independent of whether the current pair is inserted. fock_before_diis(:,:) = Fock_matrix_tc_ao_tot(:,:) + ! A level-shift retry must restart from the orbitals entering this step. + mo_l_coef_save(1:ao_num,1:mo_num) = mo_l_coef(1:ao_num,1:mo_num) + mo_r_coef_save(1:ao_num,1:mo_num) = mo_r_coef(1:ao_num,1:mo_num) + level_shift_save = level_shift_TCSCF inserted_slot = 0 rcond = 0.d0 @@ -140,14 +151,23 @@ subroutine rh_tcscf_diis() endif er_delta = maxval(abs(FQS_SQF_mo)) - er_save + best_residual = maxval(abs(FQS_SQF_mo)) + mo_l_coef_best(1:ao_num,1:mo_num) = mo_l_coef(1:ao_num,1:mo_num) + mo_r_coef_best(1:ao_num,1:mo_num) = mo_r_coef(1:ao_num,1:mo_num) - mo_l_coef_save(1:ao_num,1:mo_num) = mo_l_coef(1:ao_num,1:mo_num) - mo_r_coef_save(1:ao_num,1:mo_num) = mo_r_coef(1:ao_num,1:mo_num) - - do while((er_delta > rate_th * er_save) .and. (it > 1)) + n_retry = 0 + if((er_delta > rate_th * er_save) .and. (it > 1)) then print *, ' big or bad step ' print *, er_delta, rate_th * er_save + ! Discard entries belonging to the step that just failed, once. + call diis_reset(history) + endif + + do while((er_delta > rate_th * er_save) .and. (it > 1) .and. & + (n_retry < max_level_shift_tries)) + n_retry += 1 + mo_l_coef(1:ao_num,1:mo_num) = & mo_l_coef_save(1:ao_num,1:mo_num) mo_r_coef(1:ao_num,1:mo_num) = & @@ -165,17 +185,36 @@ subroutine rh_tcscf_diis() fock_tc_reigvec_ao(1:ao_num,1:mo_num) TOUCH mo_l_coef mo_r_coef - er_delta = maxval(abs(FQS_SQF_mo)) - er_save - - if(level_shift_TCSCF - level_shift_save > 40.d0) then - level_shift_TCSCF = level_shift_save * 4.d0 - SOFT_TOUCH level_shift_TCSCF - exit + trial_residual = maxval(abs(FQS_SQF_mo)) + if(trial_residual < best_residual) then + best_residual = trial_residual + mo_l_coef_best(1:ao_num,1:mo_num) = mo_l_coef(1:ao_num,1:mo_num) + mo_r_coef_best(1:ao_num,1:mo_num) = mo_r_coef(1:ao_num,1:mo_num) endif + er_delta = trial_residual - er_save - call diis_reset(history) enddo + ! The TC retry criterion is the residual, so keep its best trial instead + ! of blindly accepting the last level-shifted orbital pair. + if(n_retry > 0) then + mo_l_coef(1:ao_num,1:mo_num) = mo_l_coef_best(1:ao_num,1:mo_num) + mo_r_coef(1:ao_num,1:mo_num) = mo_r_coef_best(1:ao_num,1:mo_num) + TOUCH mo_l_coef mo_r_coef + er_delta = maxval(abs(FQS_SQF_mo)) - er_save + endif + + if((n_retry == max_level_shift_tries) .and. & + (er_delta > rate_th * er_save)) then + print *, ' TC-SCF level-shift retry limit reached: ', n_retry + endif + + ! Retries use temporary shifts. Keep the existing per-iteration shift + ! decay, but do not let a trial shift leak into the next SCF step. + if(n_retry > 0) then + level_shift_TCSCF = level_shift_save + SOFT_TOUCH level_shift_TCSCF + endif level_shift_TCSCF = level_shift_TCSCF * 0.5d0 SOFT_TOUCH level_shift_TCSCF @@ -188,7 +227,6 @@ subroutine rh_tcscf_diis() er_delta = er_DIIS - er_save e_save = etc_tot - level_shift_save = level_shift_TCSCF er_save = er_DIIS converged = er_DIIS .lt. dsqrt(thresh_tcscf) @@ -246,6 +284,7 @@ subroutine rh_tcscf_diis() call write_time(6) deallocate(mo_r_coef_save, mo_l_coef_save) + deallocate(mo_r_coef_best, mo_l_coef_best) deallocate(fock_before_diis, fock_extrapolated) call ezfio_set_tc_scf_tcscf_energy(TC_HF_energy) From 5cee809ffc52bc5d70948a5918183496fabc0910 Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:55:32 +0100 Subject: [PATCH 14/26] Bound QMCkl TC-SCF integration batches (cherry picked from commit bdde103cb709d89f7abec32e9a83978997e487d4) --- plugins/local/non_h_ints_mu/tc_integ.irp.f | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/plugins/local/non_h_ints_mu/tc_integ.irp.f b/plugins/local/non_h_ints_mu/tc_integ.irp.f index bcdb6c07..de368175 100644 --- a/plugins/local/non_h_ints_mu/tc_integ.irp.f +++ b/plugins/local/non_h_ints_mu/tc_integ.irp.f @@ -70,13 +70,13 @@ enddo !$OMP END DO !$OMP END PARALLEL - call total_memory(mem) - mem = max(1.d0, qp_max_mem - mem) - n_double = mem * 1.d8 if(j2e_type .eq. "Qmckl") then - ! Four result and fourteen explicit QMCkl scratch doubles per pair. - n_blocks = int(min(n_double / (n_points_extra_final_grid * 18.d0), 1.d0*n_points_final_grid)) + ! Keep QMCkl pair arrays bounded without a call for every r1 point. + n_blocks = min(32, n_points_final_grid) else + call total_memory(mem) + mem = max(1.d0, qp_max_mem - mem) + n_double = mem * 1.d8 n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), 1.d0*n_points_final_grid)) endif n_blocks = max(1, n_blocks) @@ -294,13 +294,13 @@ enddo !$OMP END DO !$OMP END PARALLEL - call total_memory(mem) - mem = max(1.d0, qp_max_mem - mem) - n_double = mem * 1.d8 if(j2e_type .eq. "Qmckl") then - ! Four result and fourteen explicit QMCkl scratch doubles per pair. - n_blocks = int(min(n_double / (n_points_extra_final_grid * 18.d0), 1.d0*n_points_final_grid)) + ! Keep QMCkl pair arrays bounded without a call for every r1 point. + n_blocks = min(32, n_points_final_grid) else + call total_memory(mem) + mem = max(1.d0, qp_max_mem - mem) + n_double = mem * 1.d8 n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), 1.d0*n_points_final_grid)) endif n_blocks = max(1, n_blocks) From 2b0285b5037257ba01eb536f4f20b1e6aa8cde84 Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:32:39 +0100 Subject: [PATCH 15/26] Balance TC-SCF left/right orbital scales (cherry picked from commit 4f3cf85713b6368f042cb27e657b0f68f33f5929) --- plugins/local/tc_scf/biorthogonal_scaling.f90 | 147 +++++++++++++ .../local/tc_scf/biorthogonal_scaling.irp.f | 28 +++ plugins/local/tc_scf/rh_tcscf_diis.irp.f | 12 +- .../tests/test_biorthogonal_scaling.f90 | 198 ++++++++++++++++++ 4 files changed, 379 insertions(+), 6 deletions(-) create mode 100644 plugins/local/tc_scf/biorthogonal_scaling.f90 create mode 100644 plugins/local/tc_scf/biorthogonal_scaling.irp.f create mode 100644 plugins/local/tc_scf/tests/test_biorthogonal_scaling.f90 diff --git a/plugins/local/tc_scf/biorthogonal_scaling.f90 b/plugins/local/tc_scf/biorthogonal_scaling.f90 new file mode 100644 index 00000000..8d0ca106 --- /dev/null +++ b/plugins/local/tc_scf/biorthogonal_scaling.f90 @@ -0,0 +1,147 @@ +module biorthogonal_scaling_module + + use, intrinsic :: ieee_arithmetic, only: ieee_is_finite + + implicit none + private + + integer, parameter, public :: scaling_success = 0 + integer, parameter, public :: scaling_bad_shape = 1 + integer, parameter, public :: scaling_bad_metric = 2 + integer, parameter, public :: scaling_bad_norm = 3 + integer, parameter, public :: scaling_bad_overlap = 4 + integer, parameter, public :: scaling_nonfinite = 5 + integer, parameter, public :: scaling_overlap_changed = 6 + + public :: balance_biorthogonal_pairs + +contains + + pure subroutine balance_biorthogonal_pairs(left, right, metric, & + left_balanced, right_balanced, & + left_scale, info) + + implicit none + + double precision, intent(in) :: left(:,:), right(:,:), metric(:,:) + double precision, intent(out) :: left_balanced(:,:), right_balanced(:,:) + double precision, intent(out) :: left_scale(:) + integer, intent(out) :: info + + double precision, allocatable :: overlap_before(:,:), overlap_after(:,:) + double precision, allocatable :: left_trial(:,:), right_trial(:,:) + double precision, allocatable :: scale_trial(:) + double precision :: left_norm_sq, right_norm_sq + double precision :: left_norm, right_norm, alpha + double precision :: metric_scale, metric_asymmetry + double precision :: overlap_scale, overlap_tolerance + double precision :: offdiag_before, offdiag_after + double precision :: diagonal_change + integer :: i, j, n, m + + info = scaling_bad_shape + n = size(left, 1) + m = size(left, 2) + if((n < 1) .or. (m < 1)) return + if((size(right,1) /= n) .or. (size(right,2) /= m)) return + if((size(metric,1) /= n) .or. (size(metric,2) /= n)) return + if((size(left_balanced,1) /= n) .or. & + (size(left_balanced,2) /= m)) return + if((size(right_balanced,1) /= n) .or. & + (size(right_balanced,2) /= m)) return + if(size(left_scale) /= m) return + + left_balanced = left + right_balanced = right + left_scale = 1.d0 + + info = scaling_nonfinite + if(.not. all(ieee_is_finite(left))) return + if(.not. all(ieee_is_finite(right))) return + if(.not. all(ieee_is_finite(metric))) return + + metric_scale = max(1.d0, maxval(abs(metric))) + metric_asymmetry = maxval(abs(metric - transpose(metric))) + info = scaling_bad_metric + if(metric_asymmetry > 100.d0 * epsilon(1.d0) * metric_scale) return + + allocate(overlap_before(m,m), overlap_after(m,m)) + allocate(left_trial(n,m), right_trial(n,m)) + allocate(scale_trial(m)) + left_trial = left + right_trial = right + scale_trial = 1.d0 + overlap_before = matmul(transpose(left), matmul(metric, right)) + info = scaling_nonfinite + if(.not. all(ieee_is_finite(overlap_before))) return + + info = scaling_bad_overlap + do i = 1, m + if(abs(overlap_before(i,i)) <= tiny(1.d0)) return + enddo + + do i = 1, m + left_norm_sq = dot_product(left(:,i), matmul(metric, left(:,i))) + right_norm_sq = dot_product(right(:,i), matmul(metric, right(:,i))) + info = scaling_nonfinite + if(.not. ieee_is_finite(left_norm_sq)) return + if(.not. ieee_is_finite(right_norm_sq)) return + + info = scaling_bad_norm + if((left_norm_sq <= 0.d0) .or. (right_norm_sq <= 0.d0)) return + + left_norm = sqrt(left_norm_sq) + right_norm = sqrt(right_norm_sq) + alpha = sqrt(right_norm) / sqrt(left_norm) + info = scaling_nonfinite + if((.not. ieee_is_finite(alpha)) .or. (alpha <= 0.d0)) return + + left_trial(:,i) = alpha * left(:,i) + right_trial(:,i) = right(:,i) / alpha + scale_trial(i) = alpha + enddo + + if(.not. all(ieee_is_finite(left_trial))) return + if(.not. all(ieee_is_finite(right_trial))) return + + overlap_after = matmul(transpose(left_trial), & + matmul(metric, right_trial)) + if(.not. all(ieee_is_finite(overlap_after))) return + + overlap_scale = max(1.d0, maxval(abs(overlap_before))) + overlap_tolerance = 100.d0 * epsilon(1.d0) * overlap_scale + diagonal_change = 0.d0 + offdiag_before = 0.d0 + offdiag_after = 0.d0 + do j = 1, m + diagonal_change = max(diagonal_change, & + abs(overlap_after(j,j) - overlap_before(j,j))) + do i = 1, m + if(i == j) cycle + offdiag_before = max(offdiag_before, abs(overlap_before(i,j))) + offdiag_after = max(offdiag_after, abs(overlap_after(i,j))) + enddo + enddo + + info = scaling_overlap_changed + if(diagonal_change > overlap_tolerance) then + left_balanced = left + right_balanced = right + left_scale = 1.d0 + return + endif + if(offdiag_after > offdiag_before + overlap_tolerance) then + left_balanced = left + right_balanced = right + left_scale = 1.d0 + return + endif + + info = scaling_success + left_balanced = left_trial + right_balanced = right_trial + left_scale = scale_trial + + end subroutine balance_biorthogonal_pairs + +end module biorthogonal_scaling_module diff --git a/plugins/local/tc_scf/biorthogonal_scaling.irp.f b/plugins/local/tc_scf/biorthogonal_scaling.irp.f new file mode 100644 index 00000000..1c082670 --- /dev/null +++ b/plugins/local/tc_scf/biorthogonal_scaling.irp.f @@ -0,0 +1,28 @@ +BEGIN_PROVIDER [ double precision, fock_tc_reigvec_ao_balanced, (ao_num, mo_num) ] +&BEGIN_PROVIDER [ double precision, fock_tc_leigvec_ao_balanced, (ao_num, mo_num) ] + + use biorthogonal_scaling_module + + implicit none + + integer :: info + double precision :: left_scale(mo_num) + + PROVIDE fock_tc_reigvec_ao fock_tc_leigvec_ao ao_overlap + + call balance_biorthogonal_pairs( fock_tc_leigvec_ao, & + fock_tc_reigvec_ao, ao_overlap, & + fock_tc_leigvec_ao_balanced, & + fock_tc_reigvec_ao_balanced, & + left_scale, info ) + + if(info == scaling_success) then + if(maxval(abs(log(left_scale))) > log(10.d0)) then + print *, ' TC-SCF left/right orbital scaling range = ', & + minval(left_scale), maxval(left_scale) + endif + else + print *, ' TC-SCF left/right orbital balancing skipped, status = ', info + endif + +END_PROVIDER diff --git a/plugins/local/tc_scf/rh_tcscf_diis.irp.f b/plugins/local/tc_scf/rh_tcscf_diis.irp.f index 175190fc..3505848c 100644 --- a/plugins/local/tc_scf/rh_tcscf_diis.irp.f +++ b/plugins/local/tc_scf/rh_tcscf_diis.irp.f @@ -127,9 +127,9 @@ subroutine rh_tcscf_diis() endif mo_l_coef(1:ao_num,1:mo_num) = & - fock_tc_leigvec_ao(1:ao_num,1:mo_num) + fock_tc_leigvec_ao_balanced(1:ao_num,1:mo_num) mo_r_coef(1:ao_num,1:mo_num) = & - fock_tc_reigvec_ao(1:ao_num,1:mo_num) + fock_tc_reigvec_ao_balanced(1:ao_num,1:mo_num) TOUCH mo_l_coef mo_r_coef er_delta = maxval(abs(FQS_SQF_mo)) - er_save @@ -144,9 +144,9 @@ subroutine rh_tcscf_diis() TOUCH Fock_matrix_tc_mo_tot fock_matrix_tc_diag_mo_tot mo_l_coef(1:ao_num,1:mo_num) = & - fock_tc_leigvec_ao(1:ao_num,1:mo_num) + fock_tc_leigvec_ao_balanced(1:ao_num,1:mo_num) mo_r_coef(1:ao_num,1:mo_num) = & - fock_tc_reigvec_ao(1:ao_num,1:mo_num) + fock_tc_reigvec_ao_balanced(1:ao_num,1:mo_num) TOUCH mo_l_coef mo_r_coef endif @@ -180,9 +180,9 @@ subroutine rh_tcscf_diis() TOUCH mo_l_coef mo_r_coef level_shift_TCSCF mo_l_coef(1:ao_num,1:mo_num) = & - fock_tc_leigvec_ao(1:ao_num,1:mo_num) + fock_tc_leigvec_ao_balanced(1:ao_num,1:mo_num) mo_r_coef(1:ao_num,1:mo_num) = & - fock_tc_reigvec_ao(1:ao_num,1:mo_num) + fock_tc_reigvec_ao_balanced(1:ao_num,1:mo_num) TOUCH mo_l_coef mo_r_coef trial_residual = maxval(abs(FQS_SQF_mo)) diff --git a/plugins/local/tc_scf/tests/test_biorthogonal_scaling.f90 b/plugins/local/tc_scf/tests/test_biorthogonal_scaling.f90 new file mode 100644 index 00000000..2b7c7c60 --- /dev/null +++ b/plugins/local/tc_scf/tests/test_biorthogonal_scaling.f90 @@ -0,0 +1,198 @@ +program test_biorthogonal_scaling + + use biorthogonal_scaling_module + + implicit none + + call test_reciprocal_balance_and_invariants() + call test_reject_overlap_growth() + call test_reject_zero_norm_without_partial_output() + call test_reject_nonsymmetric_metric() + + print *, 'PASS: biorthogonal scaling tests' + +contains + + subroutine assert_true(condition, message) + + implicit none + + logical, intent(in) :: condition + character(*), intent(in) :: message + + if(.not. condition) then + print *, 'FAIL: ', trim(message) + error stop 1 + endif + + end subroutine assert_true + + + subroutine assert_close(actual, expected, tolerance, message) + + implicit none + + double precision, intent(in) :: actual, expected, tolerance + character(*), intent(in) :: message + + call assert_true(abs(actual - expected) <= tolerance, trim(message)) + + end subroutine assert_close + + + subroutine test_reciprocal_balance_and_invariants() + + implicit none + + double precision :: left(2,2), right(2,2), metric(2,2) + double precision :: left_balanced(2,2), right_balanced(2,2) + double precision :: left_scale(2), overlap_before(2,2), overlap_after(2,2) + double precision :: projector_before(2,2), projector_after(2,2) + double precision :: left_norm, right_norm + integer :: info, i + + metric = 0.d0 + metric(1,1) = 4.d0 + metric(2,2) = 1.d0 + left = 0.d0 + right = 0.d0 + left(1,1) = 1.d8 + left(2,2) = 1.d-8 + right(1,1) = 2.5d-9 + right(2,2) = 1.d8 + + overlap_before = matmul(transpose(left), matmul(metric, right)) + projector_before = matmul(right, transpose(left)) + + call balance_biorthogonal_pairs(left, right, metric, & + left_balanced, right_balanced, & + left_scale, info) + call assert_true(info == scaling_success, 'valid reciprocal scaling rejected') + + overlap_after = matmul(transpose(left_balanced), & + matmul(metric, right_balanced)) + projector_after = matmul(right_balanced, transpose(left_balanced)) + call assert_true(maxval(abs(overlap_after-overlap_before)) < 1.d-13, & + 'cross overlap changed') + call assert_true(maxval(abs(projector_after-projector_before)) < 1.d-13, & + 'projector changed') + + do i = 1, 2 + left_norm = sqrt(dot_product(left_balanced(:,i), & + matmul(metric,left_balanced(:,i)))) + right_norm = sqrt(dot_product(right_balanced(:,i), & + matmul(metric,right_balanced(:,i)))) + call assert_close(left_norm, right_norm, 1.d-13, & + 'left/right metric norms not balanced') + call assert_true(left_scale(i) > 0.d0, 'invalid scale factor') + enddo + + end subroutine test_reciprocal_balance_and_invariants + + + subroutine test_reject_overlap_growth() + + implicit none + + double precision :: left(2,2), right(2,2), metric(2,2) + double precision :: left_balanced(2,2), right_balanced(2,2) + double precision :: left_scale(2), overlap_before(2,2), overlap_after(2,2) + integer :: info + + metric = 0.d0 + metric(1,1) = 1.d0 + metric(2,2) = 1.d0 + left = 0.d0 + left(1,1) = 100.d0 + left(2,2) = 1.d-2 + right = 0.d0 + right(1,1) = 1.d-2 + right(2,1) = 1.d-4 + right(1,2) = 1.d-6 + right(2,2) = 100.d0 + overlap_before = matmul(transpose(left), matmul(metric, right)) + + call balance_biorthogonal_pairs(left, right, metric, & + left_balanced, right_balanced, & + left_scale, info) + call assert_true(info == scaling_overlap_changed, & + 'balancing that grows off-diagonal overlap was accepted') + call assert_true(maxval(abs(left_balanced-left)) <= tiny(1.d0), & + 'rejected left matrix was partially changed') + call assert_true(maxval(abs(right_balanced-right)) <= tiny(1.d0), & + 'rejected right matrix was partially changed') + call assert_true(maxval(abs(left_scale-1.d0)) <= epsilon(1.d0), & + 'rejected scale factors were not reset') + + overlap_after = matmul(transpose(left_balanced), & + matmul(metric, right_balanced)) + call assert_true(maxval(abs(overlap_after-overlap_before)) <= tiny(1.d0), & + 'rejected overlap changed') + + end subroutine test_reject_overlap_growth + + + subroutine test_reject_zero_norm_without_partial_output() + + implicit none + + double precision :: left(2,2), right(2,2), metric(2,2) + double precision :: left_balanced(2,2), right_balanced(2,2) + double precision :: left_scale(2) + integer :: info + + metric = 0.d0 + metric(1,1) = 1.d0 + metric(2,2) = 1.d0 + left = 0.d0 + left(1,1) = 1.d0 + right = 0.d0 + right(1,1) = 1.d0 + right(2,2) = 1.d0 + + call balance_biorthogonal_pairs(left, right, metric, & + left_balanced, right_balanced, & + left_scale, info) + call assert_true(info == scaling_bad_overlap, & + 'zero pair overlap was not rejected') + call assert_true(maxval(abs(left_balanced-left)) <= tiny(1.d0), & + 'invalid input changed left output') + call assert_true(maxval(abs(right_balanced-right)) <= tiny(1.d0), & + 'invalid input changed right output') + call assert_true(maxval(abs(left_scale-1.d0)) <= epsilon(1.d0), & + 'invalid input changed scales') + + end subroutine test_reject_zero_norm_without_partial_output + + + subroutine test_reject_nonsymmetric_metric() + + implicit none + + double precision :: left(2,1), right(2,1), metric(2,2) + double precision :: left_balanced(2,1), right_balanced(2,1) + double precision :: left_scale(1) + integer :: info + + left = 0.d0 + right = 0.d0 + left(1,1) = 1.d0 + right(1,1) = 1.d0 + metric = 0.d0 + metric(1,1) = 1.d0 + metric(2,2) = 1.d0 + metric(1,2) = 0.1d0 + + call balance_biorthogonal_pairs(left, right, metric, & + left_balanced, right_balanced, & + left_scale, info) + call assert_true(info == scaling_bad_metric, & + 'nonsymmetric metric was accepted') + call assert_true(maxval(abs(left_balanced-left)) <= tiny(1.d0), & + 'bad metric changed left output') + call assert_true(maxval(abs(right_balanced-right)) <= tiny(1.d0), & + 'bad metric changed right output') + + end subroutine test_reject_nonsymmetric_metric + +end program test_biorthogonal_scaling From aaaeea5baf30a015954beb0475705519ec013e70 Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:41:10 +0100 Subject: [PATCH 16/26] Order scaling module before its QP provider (cherry picked from commit f5a629c0ce397d808a40dc514c3b2361b9bbde4a) --- ...thogonal_scaling.irp.f => biorthogonal_scaling_provider.irp.f} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename plugins/local/tc_scf/{biorthogonal_scaling.irp.f => biorthogonal_scaling_provider.irp.f} (100%) diff --git a/plugins/local/tc_scf/biorthogonal_scaling.irp.f b/plugins/local/tc_scf/biorthogonal_scaling_provider.irp.f similarity index 100% rename from plugins/local/tc_scf/biorthogonal_scaling.irp.f rename to plugins/local/tc_scf/biorthogonal_scaling_provider.irp.f From 97e976c0396d2c0a82959d3f14e76b2c3b3982b3 Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:45:27 +0100 Subject: [PATCH 17/26] Fix Intel Fortran OpenMP critical-name conflict Use an OpenMP critical name distinct from the pg_label_msg variable. Intel Fortran rejects the previous shared name; changing the lock label leaves the protected region and behavior unchanged. (cherry picked from commit d35b9b1ec5b7fa24268efdec7144182de5a40a80) --- src/symmetry_det/det_irrep.irp.f | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/symmetry_det/det_irrep.irp.f b/src/symmetry_det/det_irrep.irp.f index 86d43873..91660659 100644 --- a/src/symmetry_det/det_irrep.irp.f +++ b/src/symmetry_det/det_irrep.irp.f @@ -496,13 +496,13 @@ subroutine pg_family_fill(nsel, np, mask) if (mtot /= np) then ! Called from a parallel region: one writer at a time for the two ! messages and the shared error flag. - !$OMP CRITICAL(pg_label_msg) + !$OMP CRITICAL(pg_label_lock) write(6,'(A,I0,A,I0,A)') 'symmetry_det: family enumeration produced ', & mtot, ' members where the size was ', np, ' (internal inconsistency)' write(pg_label_msg,'(A,I0,A,I0,A)') 'family enumeration produced ', mtot, & ' members where the size was ', np, ' (internal inconsistency)' pg_label_ierr = 5 - !$OMP END CRITICAL(pg_label_msg) + !$OMP END CRITICAL(pg_label_lock) mask(1:2,1:pg_n_mo_block,1:np) = 0 return endif @@ -672,7 +672,7 @@ subroutine pg_fam_setup(np, nsel, mask, npart, nfull, fsec, psec, pn, pos, xrow, if (n > pg_det_nmax) then ! Called from a parallel region: one writer at a time for the four ! lines and the shared error flag. - !$OMP CRITICAL(pg_label_msg) + !$OMP CRITICAL(pg_label_lock) write(6,'(A,I0,A)') 'symmetry_det: one symmetry block contributes ', & n, ' occupied MOs; family enumeration supports at most 12.' write(6,'(A)') ' A block is one irrep (at most 5 MOs) unless the MO '// & @@ -682,7 +682,7 @@ subroutine pg_fam_setup(np, nsel, mask, npart, nfull, fsec, psec, pn, pos, xrow, write(pg_label_msg,'(A,I0,A)') 'one symmetry block holds ', n, & ' occupied MOs (at most 12 supported)' pg_label_ierr = 6 - !$OMP END CRITICAL(pg_label_msg) + !$OMP END CRITICAL(pg_label_lock) npart = -1 return endif @@ -742,13 +742,13 @@ subroutine pg_fam_setup(np, nsel, mask, npart, nfull, fsec, psec, pn, pos, xrow, if (msum /= np .or. nfound /= npart) then ! Called from a parallel region: one writer at a time for the two ! lines and the shared error flag. - !$OMP CRITICAL(pg_label_msg) + !$OMP CRITICAL(pg_label_lock) write(6,'(A,I0,A)') 'symmetry_det: the sector radices do not '// & 'decompose a family of ', np, ' members (internal inconsistency)' write(pg_label_msg,'(A,I0,A)') 'the sector radices do not decompose '// & 'a family of ', np, ' members (internal inconsistency)' pg_label_ierr = 7 - !$OMP END CRITICAL(pg_label_msg) + !$OMP END CRITICAL(pg_label_lock) npart = -1 return endif From 8bb658b08ae697c0c91248e3be6eddbdb358d24c Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:57:22 +0100 Subject: [PATCH 18/26] Fix double counting of explicit three-electron terms in the TC-SCF Fock matrix (cherry picked from commit db95cb61accd9cf987759488a872f9db06be9d14) --- plugins/local/tc_scf/README.md | 9 +++++++ plugins/local/tc_scf/fock_tc_mo_tot.irp.f | 31 +---------------------- 2 files changed, 10 insertions(+), 30 deletions(-) diff --git a/plugins/local/tc_scf/README.md b/plugins/local/tc_scf/README.md index 45f5c60f..f41f62df 100644 --- a/plugins/local/tc_scf/README.md +++ b/plugins/local/tc_scf/README.md @@ -1,2 +1,11 @@ Transcorrelated SCF =================== + +### Three-electron contribution + +With `three_body_h_tc=True`, each spin Fock matrix includes its +three-electron contribution. The total Fock matrix combines the spin +matrices and their three-electron terms are therefore already present. +With the default `three_body_h_tc=False` and `noL_standard=True`, +TC-SCF includes the scalar three-electron energy in its reported total +and omits the explicit three-electron term from the orbital update. diff --git a/plugins/local/tc_scf/fock_tc_mo_tot.irp.f b/plugins/local/tc_scf/fock_tc_mo_tot.irp.f index ace61fe7..870b64d7 100644 --- a/plugins/local/tc_scf/fock_tc_mo_tot.irp.f +++ b/plugins/local/tc_scf/fock_tc_mo_tot.irp.f @@ -26,6 +26,7 @@ double precision :: t0, t1 PROVIDE Fock_matrix_tc_mo_beta Fock_matrix_tc_mo_alpha + ! Each spin Fock matrix already includes its explicit three-electron term. if (all_shells_closed) then Fock_matrix_tc_mo_tot = Fock_matrix_tc_mo_alpha else @@ -81,36 +82,6 @@ enddo endif - if(three_body_h_tc) then - - PROVIDE fock_a_tot_3e_bi_orth fock_b_tot_3e_bi_orth - - ! C-O - do j = 1, elec_beta_num - do i = elec_beta_num+1, elec_alpha_num - Fock_matrix_tc_mo_tot(i,j) += 0.5d0*(fock_a_tot_3e_bi_orth(i,j) + fock_b_tot_3e_bi_orth(i,j)) - Fock_matrix_tc_mo_tot(j,i) += 0.5d0*(fock_a_tot_3e_bi_orth(j,i) + fock_b_tot_3e_bi_orth(j,i)) - enddo - enddo - ! C-V - do j = 1, elec_beta_num - do i = elec_alpha_num+1, mo_num - Fock_matrix_tc_mo_tot(i,j) += 0.5d0*(fock_a_tot_3e_bi_orth(i,j) + fock_b_tot_3e_bi_orth(i,j)) - Fock_matrix_tc_mo_tot(j,i) += 0.5d0*(fock_a_tot_3e_bi_orth(j,i) + fock_b_tot_3e_bi_orth(j,i)) - enddo - enddo - ! O-V - do j = elec_beta_num+1, elec_alpha_num - do i = elec_alpha_num+1, mo_num - Fock_matrix_tc_mo_tot(i,j) += 0.5d0*(fock_a_tot_3e_bi_orth(i,j) + fock_b_tot_3e_bi_orth(i,j)) - Fock_matrix_tc_mo_tot(j,i) += 0.5d0*(fock_a_tot_3e_bi_orth(j,i) + fock_b_tot_3e_bi_orth(j,i)) - enddo - enddo - endif - - - - if(frozen_orb_scf)then integer :: iorb,jorb do i = 1, n_core_orb From 3644c92a55f18475ddbc05d234feecdab6b72dc3 Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:57:42 +0100 Subject: [PATCH 19/26] Restore incoming TC-SCF orbitals when level-shift retries fail to improve them (cherry picked from commit 5be9f9e53fc94c0103a759240c2d0ef2b3e0ae7a) --- plugins/local/tc_scf/README.md | 8 +++ plugins/local/tc_scf/rh_tcscf_diis.irp.f | 85 +++++++++--------------- 2 files changed, 40 insertions(+), 53 deletions(-) diff --git a/plugins/local/tc_scf/README.md b/plugins/local/tc_scf/README.md index f41f62df..df5141d8 100644 --- a/plugins/local/tc_scf/README.md +++ b/plugins/local/tc_scf/README.md @@ -9,3 +9,11 @@ matrices and their three-electron terms are therefore already present. With the default `three_body_h_tc=False` and `noL_standard=True`, TC-SCF includes the scalar three-electron energy in its reported total and omits the explicit three-electron term from the orbital update. + +### Level-shift retries + +When the fallback orbital update increases the residual by more than +10%, TC-SCF clears the DIIS history and tries up to five level shifts +from the saved incoming orbitals. It accepts the first shifted update +that lowers the incoming residual. If all attempts fail, it restores +both sets of incoming orbitals and checks convergence as usual. diff --git a/plugins/local/tc_scf/rh_tcscf_diis.irp.f b/plugins/local/tc_scf/rh_tcscf_diis.irp.f index 3505848c..978cc17a 100644 --- a/plugins/local/tc_scf/rh_tcscf_diis.irp.f +++ b/plugins/local/tc_scf/rh_tcscf_diis.irp.f @@ -17,15 +17,13 @@ subroutine rh_tcscf_diis() double precision :: level_shift_save, rate_th double precision :: t0, t1 double precision :: er_DIIS, er_delta, er_save - double precision :: best_residual, trial_residual + double precision :: trial_residual double precision :: rcond double precision, allocatable :: coefficients(:) double precision, allocatable :: fock_before_diis(:,:) double precision, allocatable :: fock_extrapolated(:,:) double precision, allocatable :: mo_r_coef_save(:,:) double precision, allocatable :: mo_l_coef_save(:,:) - double precision, allocatable :: mo_r_coef_best(:,:) - double precision, allocatable :: mo_l_coef_best(:,:) logical, external :: qp_stop @@ -38,8 +36,6 @@ subroutine rh_tcscf_diis() allocate(mo_r_coef_save(ao_num,mo_num)) allocate(mo_l_coef_save(ao_num,mo_num)) - allocate(mo_r_coef_best(ao_num,mo_num)) - allocate(mo_l_coef_best(ao_num,mo_num)) allocate(fock_before_diis(ao_num,ao_num)) allocate(fock_extrapolated(ao_num,ao_num)) mo_l_coef_save = 0.d0 @@ -151,10 +147,6 @@ subroutine rh_tcscf_diis() endif er_delta = maxval(abs(FQS_SQF_mo)) - er_save - best_residual = maxval(abs(FQS_SQF_mo)) - mo_l_coef_best(1:ao_num,1:mo_num) = mo_l_coef(1:ao_num,1:mo_num) - mo_r_coef_best(1:ao_num,1:mo_num) = mo_r_coef(1:ao_num,1:mo_num) - n_retry = 0 if((er_delta > rate_th * er_save) .and. (it > 1)) then print *, ' big or bad step ' @@ -162,51 +154,39 @@ subroutine rh_tcscf_diis() ! Discard entries belonging to the step that just failed, once. call diis_reset(history) - endif - - do while((er_delta > rate_th * er_save) .and. (it > 1) .and. & - (n_retry < max_level_shift_tries)) - n_retry += 1 - - mo_l_coef(1:ao_num,1:mo_num) = & - mo_l_coef_save(1:ao_num,1:mo_num) - mo_r_coef(1:ao_num,1:mo_num) = & - mo_r_coef_save(1:ao_num,1:mo_num) - if(level_shift_TCSCF <= .1d0) then - level_shift_TCSCF = 1.d0 - else - level_shift_TCSCF = level_shift_TCSCF * 3.d0 - endif - TOUCH mo_l_coef mo_r_coef level_shift_TCSCF - - mo_l_coef(1:ao_num,1:mo_num) = & - fock_tc_leigvec_ao_balanced(1:ao_num,1:mo_num) - mo_r_coef(1:ao_num,1:mo_num) = & - fock_tc_reigvec_ao_balanced(1:ao_num,1:mo_num) - TOUCH mo_l_coef mo_r_coef - trial_residual = maxval(abs(FQS_SQF_mo)) - if(trial_residual < best_residual) then - best_residual = trial_residual - mo_l_coef_best(1:ao_num,1:mo_num) = mo_l_coef(1:ao_num,1:mo_num) - mo_r_coef_best(1:ao_num,1:mo_num) = mo_r_coef(1:ao_num,1:mo_num) + ! Retry from the incoming orbitals. Keep a trial only if it improves + ! their residual; the unextrapolated fallback already failed this test. + do while(n_retry < max_level_shift_tries) + n_retry += 1 + + mo_l_coef(1:ao_num,1:mo_num) = & + mo_l_coef_save(1:ao_num,1:mo_num) + mo_r_coef(1:ao_num,1:mo_num) = & + mo_r_coef_save(1:ao_num,1:mo_num) + if(level_shift_TCSCF <= .1d0) then + level_shift_TCSCF = 1.d0 + else + level_shift_TCSCF = level_shift_TCSCF * 3.d0 + endif + TOUCH mo_l_coef mo_r_coef level_shift_TCSCF + + mo_l_coef(1:ao_num,1:mo_num) = & + fock_tc_leigvec_ao_balanced(1:ao_num,1:mo_num) + mo_r_coef(1:ao_num,1:mo_num) = & + fock_tc_reigvec_ao_balanced(1:ao_num,1:mo_num) + TOUCH mo_l_coef mo_r_coef + + trial_residual = maxval(abs(FQS_SQF_mo)) + if(trial_residual < er_save) exit + enddo + + if(.not. (trial_residual < er_save)) then + mo_l_coef(:,:) = mo_l_coef_save(:,:) + mo_r_coef(:,:) = mo_r_coef_save(:,:) + TOUCH mo_l_coef mo_r_coef + print *, ' TC-SCF retries did not improve the residual; restored incoming orbitals' endif - er_delta = trial_residual - er_save - - enddo - - ! The TC retry criterion is the residual, so keep its best trial instead - ! of blindly accepting the last level-shifted orbital pair. - if(n_retry > 0) then - mo_l_coef(1:ao_num,1:mo_num) = mo_l_coef_best(1:ao_num,1:mo_num) - mo_r_coef(1:ao_num,1:mo_num) = mo_r_coef_best(1:ao_num,1:mo_num) - TOUCH mo_l_coef mo_r_coef - er_delta = maxval(abs(FQS_SQF_mo)) - er_save - endif - - if((n_retry == max_level_shift_tries) .and. & - (er_delta > rate_th * er_save)) then - print *, ' TC-SCF level-shift retry limit reached: ', n_retry endif ! Retries use temporary shifts. Keep the existing per-iteration shift @@ -284,7 +264,6 @@ subroutine rh_tcscf_diis() call write_time(6) deallocate(mo_r_coef_save, mo_l_coef_save) - deallocate(mo_r_coef_best, mo_l_coef_best) deallocate(fock_before_diis, fock_extrapolated) call ezfio_set_tc_scf_tcscf_energy(TC_HF_energy) From c79b38117209144ceb2e037d3441d42ceebd39a6 Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:25:30 +0100 Subject: [PATCH 20/26] Verify TC orbital rescaling in wider precision (cherry picked from commit cb8ccc5d5527e3dc08dd7834b31e982ec01c58c4) --- plugins/local/tc_scf/biorthogonal_scaling.f90 | 30 ++++++++++++++++--- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/plugins/local/tc_scf/biorthogonal_scaling.f90 b/plugins/local/tc_scf/biorthogonal_scaling.f90 index 8d0ca106..559abe1b 100644 --- a/plugins/local/tc_scf/biorthogonal_scaling.f90 +++ b/plugins/local/tc_scf/biorthogonal_scaling.f90 @@ -12,6 +12,7 @@ module biorthogonal_scaling_module integer, parameter, public :: scaling_bad_overlap = 4 integer, parameter, public :: scaling_nonfinite = 5 integer, parameter, public :: scaling_overlap_changed = 6 + integer, parameter :: wide_real = selected_real_kind(18) public :: balance_biorthogonal_pairs @@ -31,12 +32,15 @@ pure subroutine balance_biorthogonal_pairs(left, right, metric, & double precision, allocatable :: overlap_before(:,:), overlap_after(:,:) double precision, allocatable :: left_trial(:,:), right_trial(:,:) double precision, allocatable :: scale_trial(:) + real(wide_real), allocatable :: metric_wide(:,:) + real(wide_real), allocatable :: left_wide(:), right_wide(:) double precision :: left_norm_sq, right_norm_sq double precision :: left_norm, right_norm, alpha double precision :: metric_scale, metric_asymmetry double precision :: overlap_scale, overlap_tolerance double precision :: offdiag_before, offdiag_after - double precision :: diagonal_change + real(wide_real) :: overlap_before_diag, overlap_after_diag + real(wide_real) :: diagonal_change, overlap_tolerance_wide integer :: i, j, n, m info = scaling_bad_shape @@ -110,12 +114,30 @@ pure subroutine balance_biorthogonal_pairs(left, right, metric, & overlap_scale = max(1.d0, maxval(abs(overlap_before))) overlap_tolerance = 100.d0 * epsilon(1.d0) * overlap_scale - diagonal_change = 0.d0 + overlap_tolerance_wide = real(overlap_tolerance, wide_real) + diagonal_change = 0._wide_real offdiag_before = 0.d0 offdiag_after = 0.d0 + allocate(metric_wide(n,n), left_wide(n), right_wide(n)) + metric_wide = real(metric, wide_real) do j = 1, m + ! The left and right scales cancel in this overlap. Wider sums keep + ! rounding from making a valid rescaling look like a failure. + left_wide = real(left(:,j), wide_real) + right_wide = real(right(:,j), wide_real) + overlap_before_diag = dot_product(left_wide, & + matmul(metric_wide, right_wide)) + left_wide = real(left_trial(:,j), wide_real) + right_wide = real(right_trial(:,j), wide_real) + overlap_after_diag = dot_product(left_wide, & + matmul(metric_wide, right_wide)) + if((.not. ieee_is_finite(overlap_before_diag)) .or. & + (.not. ieee_is_finite(overlap_after_diag))) then + info = scaling_nonfinite + return + endif diagonal_change = max(diagonal_change, & - abs(overlap_after(j,j) - overlap_before(j,j))) + abs(overlap_after_diag - overlap_before_diag)) do i = 1, m if(i == j) cycle offdiag_before = max(offdiag_before, abs(overlap_before(i,j))) @@ -124,7 +146,7 @@ pure subroutine balance_biorthogonal_pairs(left, right, metric, & enddo info = scaling_overlap_changed - if(diagonal_change > overlap_tolerance) then + if(diagonal_change > overlap_tolerance_wide) then left_balanced = left right_balanced = right left_scale = 1.d0 From 5ec43dde735a00c1d025ce4b08c7b5285c26b0ca Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:46:52 +0100 Subject: [PATCH 21/26] Stop TC-SCF on the orbital residual in orthonormal AO coordinates (cherry picked from commit 831068b3348e09ab84f88c51b91c6e1a37e9f51e) --- plugins/local/tc_scf/EZFIO.cfg | 2 +- plugins/local/tc_scf/diis_tcscf.irp.f | 40 ++++++++++++++++++++++++ plugins/local/tc_scf/rh_tcscf_diis.irp.f | 20 +++++++++++- 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/plugins/local/tc_scf/EZFIO.cfg b/plugins/local/tc_scf/EZFIO.cfg index e3d24338..4594d53a 100644 --- a/plugins/local/tc_scf/EZFIO.cfg +++ b/plugins/local/tc_scf/EZFIO.cfg @@ -23,7 +23,7 @@ default: 0. [thresh_tcscf] type: Threshold -doc: Threshold on the convergence of the Hartree Fock energy. +doc: TC-SCF converges when the largest singular value of the residual in orthonormal AO coordinates is below the square root of this value. interface: ezfio,provider,ocaml default: 1.e-8 diff --git a/plugins/local/tc_scf/diis_tcscf.irp.f b/plugins/local/tc_scf/diis_tcscf.irp.f index ccc8eb15..b9e9491c 100644 --- a/plugins/local/tc_scf/diis_tcscf.irp.f +++ b/plugins/local/tc_scf/diis_tcscf.irp.f @@ -145,3 +145,43 @@ ! --- + +subroutine tc_orthogonalize_span(coef, x) + implicit none + double precision, intent(in) :: coef(ao_num,mo_num) + double precision, intent(out) :: x(ao_num,mo_num) + double precision :: scale + double precision, allocatable :: gram(:,:) + integer :: i, info + + ! Strip arbitrary column scales before forming the overlap matrix. + do i=1,mo_num + scale = maxval(abs(coef(:,i))) + if (scale == 0.d0) error stop 'Empty TC orbital column' + x(:,i) = coef(:,i)/scale + enddo + allocate(gram(mo_num,mo_num)) + gram = matmul(transpose(x),matmul(ao_overlap,x)) + call dpotrf('U',mo_num,gram,mo_num,info) + if (info /= 0) error stop 'Cannot orthonormalize truncated TC orbital space' + call dtrsm('R','U','N','N',ao_num,mo_num,1.d0,gram,mo_num,x,ao_num) +end + +subroutine tc_ao_residual_norm(x_left, x_right, residual) + use ieee_arithmetic, only: ieee_is_finite + implicit none + double precision, intent(in) :: x_left(ao_num,mo_num), x_right(ao_num,mo_num) + double precision, intent(out) :: residual + double precision, allocatable :: projected(:,:), singular(:), work(:) + double precision :: unused_u(1), unused_v(1) + integer :: info + + allocate(projected(mo_num,mo_num), singular(mo_num), work(5*mo_num)) + projected = matmul(transpose(x_left),matmul(FQS_SQF_ao,x_right)) + if (.not.all(ieee_is_finite(projected))) error stop 'Nonfinite AO residual' + ! Only the singular values are needed; LAPACK returns the largest first. + call dgesvd('N','N',mo_num,mo_num,projected,mo_num,singular, & + unused_u,1,unused_v,1,work,size(work),info) + if (info /= 0) error stop 'AO residual singular value calculation failed' + residual = singular(1) +end diff --git a/plugins/local/tc_scf/rh_tcscf_diis.irp.f b/plugins/local/tc_scf/rh_tcscf_diis.irp.f index 978cc17a..ca87fec8 100644 --- a/plugins/local/tc_scf/rh_tcscf_diis.irp.f +++ b/plugins/local/tc_scf/rh_tcscf_diis.irp.f @@ -25,6 +25,8 @@ subroutine rh_tcscf_diis() double precision, allocatable :: mo_r_coef_save(:,:) double precision, allocatable :: mo_l_coef_save(:,:) + double precision, allocatable :: x_left(:,:), x_right(:,:) + double precision :: ao_residual logical, external :: qp_stop PROVIDE level_shift_TCSCF @@ -41,6 +43,16 @@ subroutine rh_tcscf_diis() mo_l_coef_save = 0.d0 mo_r_coef_save = 0.d0 + allocate(x_left(ao_num,mo_num), x_right(ao_num,mo_num)) + if (mo_num == ao_ortho_canonical_num) then + x_left = ao_ortho_canonical_coef(:,1:mo_num) + x_right = x_left + else + ! A truncated MO calculation tests only the supplied left/right spaces. + call tc_orthogonalize_span(mo_l_coef, x_left) + call tc_orthogonalize_span(mo_r_coef, x_right) + endif + call diis_initialize(history, ao_num, max_dim_DIIS_TCSCF, info) if(info /= diis_success) then stop 'TC-SCF DIIS history initialization failed' @@ -75,6 +87,9 @@ subroutine rh_tcscf_diis() write(6, '(I4,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, F16.10,1X, I4,1X, F8.2)') & it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, er_DIIS, level_shift_tcscf, history_count, (t1-t0)/60.d0 + call tc_ao_residual_norm(x_left, x_right, ao_residual) + write(6,'(A,I5,1X,ES22.14)') ' TC-SCF AO residual ', it, ao_residual + PROVIDE FQS_SQF_ao Fock_matrix_tc_ao_tot converged = .false. @@ -209,7 +224,9 @@ subroutine rh_tcscf_diis() e_save = etc_tot er_save = er_DIIS - converged = er_DIIS .lt. dsqrt(thresh_tcscf) + call tc_ao_residual_norm(x_left, x_right, ao_residual) + write(6,'(A,I5,1X,ES22.14)') ' TC-SCF AO residual ', it, ao_residual + converged = ao_residual .lt. dsqrt(thresh_tcscf) history_count = diis_count(history) call wall_time(t1) @@ -227,6 +244,7 @@ subroutine rh_tcscf_diis() write(json_unit, json_real_fmt) ' E(1e) ', etc_1e write(json_unit, json_real_fmt) ' E(2e) ', etc_2e write(json_unit, json_real_fmt) ' E(3e) ', etc_3e + write(json_unit, json_real_fmt) ' AO residual ', ao_residual write(json_unit, json_real_fmt) ' delta Energy ', e_delta write(json_unit, json_real_fmt) ' DIIS error ', er_DIIS write(json_unit, json_real_fmt) ' level_shift ', level_shift_tcscf From 5f3f1ffd1b8fd38337136a923fc429f2a83126d7 Mon Sep 17 00:00:00 2001 From: "matteo.peria" <82453188+matteo-peria@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:29:38 +0100 Subject: [PATCH 22/26] Compute save-memory TC gradient integrals in a single pass Reuse each block of Jastrow derivatives for both the gradient and gradient-squared AO integrals. Keep the bounded QMCkl batches and the existing one-shot integration path. (cherry picked from commit bd48e00b3e1384f06dbab031760f4f0e0a371961) --- plugins/local/non_h_ints_mu/tc_integ.irp.f | 193 +----------------- .../local/non_h_ints_mu/tc_integ_num.irp.f | 151 +++++--------- 2 files changed, 55 insertions(+), 289 deletions(-) diff --git a/plugins/local/non_h_ints_mu/tc_integ.irp.f b/plugins/local/non_h_ints_mu/tc_integ.irp.f index de368175..71a0200e 100644 --- a/plugins/local/non_h_ints_mu/tc_integ.irp.f +++ b/plugins/local/non_h_ints_mu/tc_integ.irp.f @@ -46,102 +46,10 @@ print *, ' Numerical integration over r1 and r2 will be performed' if(tc_save_mem) then - - integer :: n_blocks, n_rest, n_pass - integer :: i_blocks, i_rest, i_pass, ii - double precision :: mem, n_double - double precision, allocatable :: tmp(:,:,:), xx(:,:) - double precision, allocatable :: tmp_grad1_u12(:,:,:) - - PROVIDE final_weight_at_r_vector_extra aos_in_r_array_extra - - allocate(tmp(n_points_extra_final_grid,ao_num,ao_num)) - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (j, i, jpoint) & - !$OMP SHARED (tmp, ao_num, n_points_extra_final_grid, final_weight_at_r_vector_extra, aos_in_r_array_extra_transp) - !$OMP DO COLLAPSE(2) - do j = 1, ao_num - do i = 1, ao_num - do jpoint = 1, n_points_extra_final_grid - tmp(jpoint,i,j) = final_weight_at_r_vector_extra(jpoint) * aos_in_r_array_extra_transp(jpoint,i) * aos_in_r_array_extra_transp(jpoint,j) - enddo - enddo - enddo - !$OMP END DO - !$OMP END PARALLEL - if(j2e_type .eq. "Qmckl") then - ! Keep QMCkl pair arrays bounded without a call for every r1 point. - n_blocks = min(32, n_points_final_grid) - else - call total_memory(mem) - mem = max(1.d0, qp_max_mem - mem) - n_double = mem * 1.d8 - n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), 1.d0*n_points_final_grid)) - endif - n_blocks = max(1, n_blocks) - n_rest = int(mod(n_points_final_grid, n_blocks)) - n_pass = int((n_points_final_grid - n_rest) / n_blocks) - call write_int(6, n_pass, 'Number of passes') - call write_int(6, n_blocks, 'Size of the blocks') - call write_int(6, n_rest, 'Size of the last block') - allocate(tmp_grad1_u12(n_points_extra_final_grid,n_blocks,3), xx(n_points_extra_final_grid,n_blocks)) - do i_pass = 1, n_pass - ii = (i_pass-1)*n_blocks + 1 - if(j2e_type .eq. "Qmckl") then - call get_grad1_u12_withsq_qmckl_block(ii, n_blocks, n_points_extra_final_grid, tmp_grad1_u12(1,1,1), tmp_grad1_u12(1,1,2), tmp_grad1_u12(1,1,3), xx(1,1)) - else - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_blocks, ipoint) & - !$OMP SHARED (n_blocks, n_points_extra_final_grid, ii, final_grid_points, xx, tmp_grad1_u12) - !$OMP DO - do i_blocks = 1, n_blocks - ipoint = ii - 1 + i_blocks ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_blocks,1), tmp_grad1_u12(1,i_blocks,2), tmp_grad1_u12(1,i_blocks,3), xx(1,i_blocks)) - enddo - !$OMP END DO - !$OMP END PARALLEL - endif - do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, n_blocks, n_points_extra_final_grid, 1.d0 & - , tmp(1,1,1), n_points_extra_final_grid, tmp_grad1_u12(1,1,m), n_points_extra_final_grid & - , 0.d0, int2_grad1_u12_ao(1,1,ii,m), ao_num*ao_num) - enddo - enddo - deallocate(tmp_grad1_u12, xx) - if(n_rest .gt. 0) then - allocate(tmp_grad1_u12(n_points_extra_final_grid,n_rest,3), xx(n_points_extra_final_grid,n_rest)) - ii = n_pass*n_blocks + 1 - if(j2e_type .eq. "Qmckl") then - call get_grad1_u12_withsq_qmckl_block(ii, n_rest, n_points_extra_final_grid, tmp_grad1_u12(1,1,1), tmp_grad1_u12(1,1,2), tmp_grad1_u12(1,1,3), xx(1,1)) - else - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_rest, ipoint) & - !$OMP SHARED (n_rest, n_points_extra_final_grid, ii, final_grid_points, xx, tmp_grad1_u12) - !$OMP DO - do i_rest = 1, n_rest - ipoint = ii - 1 + i_rest ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_rest,1), tmp_grad1_u12(1,i_rest,2), tmp_grad1_u12(1,i_rest,3), xx(1,i_rest)) - enddo - !$OMP END DO - !$OMP END PARALLEL - endif - do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, n_rest, n_points_extra_final_grid, 1.d0 & - , tmp(1,1,1), n_points_extra_final_grid, tmp_grad1_u12(1,1,m), n_points_extra_final_grid & - , 0.d0, int2_grad1_u12_ao(1,1,ii,m), ao_num*ao_num) - enddo - deallocate(tmp_grad1_u12, xx) - endif - deallocate(tmp) - + PROVIDE int2_grad1_u12_ao_num + int2_grad1_u12_ao = int2_grad1_u12_ao_num else - ! TODO combine 1shot & int2_grad1_u12_ao_num -! PROVIDE int2_grad1_u12_ao_num -! int2_grad1_u12_ao = int2_grad1_u12_ao_num - PROVIDE int2_grad1_u12_ao_num_1shot + PROVIDE int2_grad1_u12_ao_num_1shot int2_grad1_u12_ao = int2_grad1_u12_ao_num_1shot endif @@ -270,99 +178,10 @@ print *, ' Numerical integration over r1 and r2 will be performed' if(tc_save_mem) then - - integer :: n_blocks, n_rest, n_pass - integer :: i_blocks, i_rest, i_pass, ii - double precision :: mem, n_double - double precision, allocatable :: tmp(:,:,:), xx(:,:,:) - double precision, allocatable :: tmp_grad1_u12_squared(:,:) - - PROVIDE final_weight_at_r_vector_extra aos_in_r_array_extra - - allocate(tmp(n_points_extra_final_grid,ao_num,ao_num)) - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (j, i, jpoint) & - !$OMP SHARED (tmp, ao_num, n_points_extra_final_grid, final_weight_at_r_vector_extra, aos_in_r_array_extra_transp) - !$OMP DO COLLAPSE(2) - do j = 1, ao_num - do i = 1, ao_num - do jpoint = 1, n_points_extra_final_grid - tmp(jpoint,i,j) = final_weight_at_r_vector_extra(jpoint) * aos_in_r_array_extra_transp(jpoint,i) * aos_in_r_array_extra_transp(jpoint,j) - enddo - enddo - enddo - !$OMP END DO - !$OMP END PARALLEL - if(j2e_type .eq. "Qmckl") then - ! Keep QMCkl pair arrays bounded without a call for every r1 point. - n_blocks = min(32, n_points_final_grid) - else - call total_memory(mem) - mem = max(1.d0, qp_max_mem - mem) - n_double = mem * 1.d8 - n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), 1.d0*n_points_final_grid)) - endif - n_blocks = max(1, n_blocks) - n_rest = int(mod(n_points_final_grid, n_blocks)) - n_pass = int((n_points_final_grid - n_rest) / n_blocks) - call write_int(6, n_pass, 'Number of passes') - call write_int(6, n_blocks, 'Size of the blocks') - call write_int(6, n_rest, 'Size of the last block') - allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_blocks), xx(n_points_extra_final_grid,n_blocks,3)) - do i_pass = 1, n_pass - ii = (i_pass-1)*n_blocks + 1 - if(j2e_type .eq. "Qmckl") then - call get_grad1_u12_withsq_qmckl_block(ii, n_blocks, n_points_extra_final_grid, xx(1,1,1), xx(1,1,2), xx(1,1,3), tmp_grad1_u12_squared(1,1)) - else - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_blocks, ipoint) & - !$OMP SHARED (n_blocks, n_points_extra_final_grid, ii, xx, final_grid_points, tmp_grad1_u12_squared) - !$OMP DO - do i_blocks = 1, n_blocks - ipoint = ii - 1 + i_blocks ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, xx(1,i_blocks,1), xx(1,i_blocks,2), xx(1,i_blocks,3), tmp_grad1_u12_squared(1,i_blocks)) - enddo - !$OMP END DO - !$OMP END PARALLEL - endif - call dgemm( "T", "N", ao_num*ao_num, n_blocks, n_points_extra_final_grid, -0.5d0 & - , tmp(1,1,1), n_points_extra_final_grid, tmp_grad1_u12_squared(1,1), n_points_extra_final_grid & - , 0.d0, int2_grad1_u12_square_ao(1,1,ii), ao_num*ao_num) - enddo - deallocate(tmp_grad1_u12_squared, xx) - if(n_rest .gt. 0) then - ii = n_pass*n_blocks + 1 - allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_rest), xx(n_points_extra_final_grid,n_rest,3)) - if(j2e_type .eq. "Qmckl") then - call get_grad1_u12_withsq_qmckl_block(ii, n_rest, n_points_extra_final_grid, xx(1,1,1), xx(1,1,2), xx(1,1,3), tmp_grad1_u12_squared(1,1)) - else - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_rest, ipoint) & - !$OMP SHARED (n_rest, n_points_extra_final_grid, ii, xx, final_grid_points, tmp_grad1_u12_squared) - !$OMP DO - do i_rest = 1, n_rest - ipoint = ii - 1 + i_rest ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, xx(1,i_rest,1), xx(1,i_rest,2), xx(1,i_rest,3), tmp_grad1_u12_squared(1,i_rest)) - enddo - !$OMP END DO - !$OMP END PARALLEL - endif - call dgemm( "T", "N", ao_num*ao_num, n_rest, n_points_extra_final_grid, -0.5d0 & - , tmp(1,1,1), n_points_extra_final_grid, tmp_grad1_u12_squared(1,1), n_points_extra_final_grid & - , 0.d0, int2_grad1_u12_square_ao(1,1,ii), ao_num*ao_num) - deallocate(tmp_grad1_u12_squared, xx) - endif - deallocate(tmp) - + PROVIDE int2_grad1_u12_square_ao_num + int2_grad1_u12_square_ao = int2_grad1_u12_square_ao_num else - - ! TODO combine 1shot & int2_grad1_u12_square_ao_num -! PROVIDE int2_grad1_u12_square_ao_num -! int2_grad1_u12_square_ao = int2_grad1_u12_square_ao_num - PROVIDE int2_grad1_u12_square_ao_num_1shot + PROVIDE int2_grad1_u12_square_ao_num_1shot int2_grad1_u12_square_ao = int2_grad1_u12_square_ao_num_1shot endif diff --git a/plugins/local/non_h_ints_mu/tc_integ_num.irp.f b/plugins/local/non_h_ints_mu/tc_integ_num.irp.f index 043d2b5e..35a337b4 100644 --- a/plugins/local/non_h_ints_mu/tc_integ_num.irp.f +++ b/plugins/local/non_h_ints_mu/tc_integ_num.irp.f @@ -1,4 +1,3 @@ -use sizet ! --- @@ -14,18 +13,14 @@ END_DOC implicit none - integer :: m - integer(size_t) :: ipoint, i, j, jpoint - integer(size_t) :: n_blocks, n_rest, n_pass - integer(size_t) :: i_blocks, i_rest, i_pass, ii + integer :: ipoint, i, j, m, jpoint + integer :: n_blocks, n_this + integer :: i_blocks, ii double precision :: time0, time1 double precision :: mem, n_double double precision, allocatable :: tmp(:,:,:) double precision, allocatable :: tmp_grad1_u12(:,:,:), tmp_grad1_u12_squared(:,:) - ! TODO - ! tmp_grad1_u12_squared get be obtained from tmp_grad1_u12 - print*, ' providing int2_grad1_u12_ao_num & int2_grad1_u12_square_ao_num ...' call wall_time(time0) @@ -36,7 +31,7 @@ !$OMP DEFAULT (NONE) & !$OMP PRIVATE (j, i, jpoint) & !$OMP SHARED (tmp, ao_num, n_points_extra_final_grid, final_weight_at_r_vector_extra, aos_in_r_array_extra_transp) - !$OMP DO SCHEDULE (static) + !$OMP DO COLLAPSE(2) do j = 1, ao_num do i = 1, ao_num do jpoint = 1, n_points_extra_final_grid @@ -47,94 +42,51 @@ !$OMP END DO !$OMP END PARALLEL - call total_memory(mem) - mem = max(1.d0, qp_max_mem - mem) - n_double = mem * 1.d8 - n_blocks = int(min(n_double / (n_points_extra_final_grid * 4.d0), & - 1.d0*n_points_final_grid), size_t) - n_rest = int(mod(n_points_final_grid, n_blocks), size_t) - n_pass = int((n_points_final_grid - n_rest) / n_blocks, size_t) - - call write_int(6, int(n_pass, 4), 'Number of passes') - call write_int(6, int(n_blocks, 4), 'Size of the blocks') - call write_int(6, int(n_rest, 4), 'Size of the last block') + if (j2e_type == 'Qmckl') then + ! Bound the number of electron pairs held by the QMCkl context. + n_blocks = min(32, n_points_final_grid) + else + call total_memory(mem) + mem = max(1.d0, qp_max_mem - mem) + n_double = mem * 1.d8 + n_blocks = max(1, int(min(n_double / (4.d0 * n_points_extra_final_grid), & + dble(n_points_final_grid)))) + endif - - allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_blocks)) + call write_int(6, n_blocks, 'Size of the blocks') allocate(tmp_grad1_u12(n_points_extra_final_grid,n_blocks,3)) - - do i_pass = 1, n_pass - ii = (i_pass-1)*n_blocks + 1 - - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_blocks, ipoint) & - !$OMP SHARED (n_blocks, n_points_extra_final_grid, ii, final_grid_points, tmp_grad1_u12, tmp_grad1_u12_squared) - !$OMP DO - do i_blocks = 1, n_blocks - ipoint = ii - 1 + i_blocks ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_blocks,1) & - , tmp_grad1_u12(1,i_blocks,2) & - , tmp_grad1_u12(1,i_blocks,3) & - , tmp_grad1_u12_squared(1,i_blocks)) - enddo - !$OMP END DO - !$OMP END PARALLEL + allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_blocks)) + + do ii = 1, n_points_final_grid, n_blocks + n_this = min(n_blocks, n_points_final_grid - ii + 1) + if (j2e_type == 'Qmckl') then + call get_grad1_u12_withsq_qmckl_block(ii, n_this, n_points_extra_final_grid, & + tmp_grad1_u12(1,1,1), tmp_grad1_u12(1,1,2), tmp_grad1_u12(1,1,3), & + tmp_grad1_u12_squared(1,1)) + else + !$OMP PARALLEL DO DEFAULT(NONE) PRIVATE(i_blocks,ipoint) & + !$OMP SHARED(ii,n_this,n_points_extra_final_grid,tmp_grad1_u12,tmp_grad1_u12_squared) + do i_blocks = 1, n_this + ipoint = ii + i_blocks - 1 + call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, & + tmp_grad1_u12(1,i_blocks,1), tmp_grad1_u12(1,i_blocks,2), & + tmp_grad1_u12(1,i_blocks,3), tmp_grad1_u12_squared(1,i_blocks)) + enddo + !$OMP END PARALLEL DO + endif + ! Use both results before reusing the pair-grid workspace for the next block. do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, int(n_blocks, 4) & - , int(n_points_extra_final_grid, 4), 1.d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12(1,1,m), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_ao_num(1,1,ii,m), ao_num*ao_num) + call dgemm('T','N',ao_num*ao_num,n_this,n_points_extra_final_grid,1.d0, & + tmp,n_points_extra_final_grid,tmp_grad1_u12(1,1,m),n_points_extra_final_grid, & + 0.d0,int2_grad1_u12_ao_num(1,1,ii,m),ao_num*ao_num) enddo - call dgemm( "T", "N", ao_num*ao_num, int(n_blocks, 4) & - , int(n_points_extra_final_grid, 4), -0.5d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12_squared(1,1), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_square_ao_num(1,1,ii), ao_num*ao_num) + call dgemm('T','N',ao_num*ao_num,n_this,n_points_extra_final_grid,-0.5d0, & + tmp,n_points_extra_final_grid,tmp_grad1_u12_squared,n_points_extra_final_grid, & + 0.d0,int2_grad1_u12_square_ao_num(1,1,ii),ao_num*ao_num) enddo - - deallocate(tmp_grad1_u12, tmp_grad1_u12_squared) - - if(n_rest .gt. 0) then - - allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_rest)) - allocate(tmp_grad1_u12(n_points_extra_final_grid,n_rest,3)) - - ii = n_pass*n_blocks + 1 - - !$OMP PARALLEL & - !$OMP DEFAULT (NONE) & - !$OMP PRIVATE (i_rest, ipoint) & - !$OMP SHARED (n_rest, n_points_extra_final_grid, ii, final_grid_points, tmp_grad1_u12, tmp_grad1_u12_squared) - !$OMP DO - do i_rest = 1, n_rest - ipoint = ii - 1 + i_rest ! r1 - call get_grad1_u12_withsq_r1_seq(ipoint, n_points_extra_final_grid, tmp_grad1_u12(1,i_rest,1) & - , tmp_grad1_u12(1,i_rest,2) & - , tmp_grad1_u12(1,i_rest,3) & - , tmp_grad1_u12_squared(1,i_rest)) - enddo - !$OMP END DO - !$OMP END PARALLEL - - do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, int(n_rest, 4) & - , int(n_points_extra_final_grid, 4), 1.d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12(1,1,m), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_ao_num(1,1,ii,m), ao_num*ao_num) - enddo - call dgemm( "T", "N", ao_num*ao_num, int(n_rest, 4) & - , int(n_points_extra_final_grid, 4), -0.5d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , tmp_grad1_u12_squared(1,1), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_square_ao_num(1,1,ii), ao_num*ao_num) - - deallocate(tmp_grad1_u12, tmp_grad1_u12_squared) - endif + deallocate(tmp_grad1_u12, tmp_grad1_u12_squared) deallocate(tmp) call wall_time(time1) @@ -157,8 +109,7 @@ END_DOC implicit none - integer :: m - integer(size_t) :: ipoint, i, j, jpoint + integer :: ipoint, i, j, m, jpoint double precision :: time0, time1 double precision, allocatable :: tmp(:,:,:) @@ -185,19 +136,15 @@ !$OMP END PARALLEL do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, int(n_points_final_grid, 4) & - , int(n_points_extra_final_grid, 4), 1.d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , grad1_u12_num(1,1,m), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_ao_num_1shot(1,1,1,m), ao_num*ao_num) + call dgemm( "T", "N", ao_num*ao_num, n_points_final_grid, n_points_extra_final_grid, 1.d0 & + , tmp(1,1,1), n_points_extra_final_grid, grad1_u12_num(1,1,m), n_points_extra_final_grid & + , 0.d0, int2_grad1_u12_ao_num_1shot(1,1,1,m), ao_num*ao_num) enddo FREE grad1_u12_num - call dgemm( "T", "N", ao_num*ao_num, int(n_points_final_grid, 4) & - , int(n_points_extra_final_grid, 4), -0.5d0 & - , tmp(1,1,1), int(n_points_extra_final_grid, 4) & - , grad1_u12_squared_num(1,1), int(n_points_extra_final_grid, 4) & - , 0.d0, int2_grad1_u12_square_ao_num_1shot(1,1,1), ao_num*ao_num) + call dgemm( "T", "N", ao_num*ao_num, n_points_final_grid, n_points_extra_final_grid, -0.5d0 & + , tmp(1,1,1), n_points_extra_final_grid, grad1_u12_squared_num(1,1), n_points_extra_final_grid & + , 0.d0, int2_grad1_u12_square_ao_num_1shot(1,1,1), ao_num*ao_num) FREE grad1_u12_squared_num deallocate(tmp) From 32a670ee4a89dc24163161b78cd5b126b79fbe91 Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 21:15:53 +0100 Subject: [PATCH 23/26] non_h_ints_mu: re-apply the size_t conventions to the ported PR #439 code The qp3 branch converted integer kinds with PR #437 (see docs/source/programmers_guide/conventions.rst, "Integer kinds"), which the dev-stable code of PR #439 predates. Adapt the three files the conversion and the port both touch: - tc_integ.irp.f: keep use sizet and the 64-bit grid-index declarations of the surviving providers. - tc_integ_num.irp.f: n_blocks, n_this, ii, i_blocks and the grid indices are integer(size_t); int(x, 4) at the dgemm and write_int boundaries; the memory bound is computed in double precision then converted once. - jast_deriv_utils_vect.irp.f: the new get_grad1_u12_withsq_qmckl_block takes 64-bit grid counts and indices, uses 64-bit loop counters and size_t literals, and drops the integer*8/int(x,8) spellings. No logic change: the diff against the dev-stable blobs contains integer kinds and casts only. --- .../non_h_ints_mu/jast_deriv_utils_vect.irp.f | 33 +++++++------- plugins/local/non_h_ints_mu/tc_integ.irp.f | 7 ++- .../local/non_h_ints_mu/tc_integ_num.irp.f | 43 +++++++++++-------- 3 files changed, 47 insertions(+), 36 deletions(-) diff --git a/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f b/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f index 76299adb..14d9b4fe 100644 --- a/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f +++ b/plugins/local/non_h_ints_mu/jast_deriv_utils_vect.irp.f @@ -157,15 +157,16 @@ subroutine get_grad1_u12_withsq_qmckl_block(ipoint_first, n_grid1, n_grid2, resx ! The shared QMCkl context is updated once, outside OpenMP regions. END_DOC + use sizet use qmckl implicit none - integer, intent(in) :: ipoint_first, n_grid1, n_grid2 + integer(size_t), intent(in) :: ipoint_first, n_grid1, n_grid2 double precision, intent(out) :: resx(n_grid2,n_grid1), resy(n_grid2,n_grid1) double precision, intent(out) :: resz(n_grid2,n_grid1), res (n_grid2,n_grid1) - integer :: i_grid1, ipoint, jpoint - integer*8 :: k, n_points + integer(size_t) :: i_grid1, ipoint, jpoint + integer(size_t) :: k, n_points double precision :: dx, dy, dz, fac_en double precision, allocatable :: rij(:,:,:), gl(:,:,:) integer(qmckl_exit_code) :: rc @@ -174,61 +175,61 @@ subroutine get_grad1_u12_withsq_qmckl_block(ipoint_first, n_grid1, n_grid2, resx PROVIDE elec_num PROVIDE final_grid_points final_grid_points_extra - n_points = int(n_grid1,8) * int(n_grid2,8) + n_points = n_grid1 * n_grid2 allocate(rij(3,2,n_points), gl(2,4,n_points)) - k = 0_8 + k = 0_size_t do i_grid1 = 1, n_grid1 ipoint = ipoint_first + i_grid1 - 1 do jpoint = 1, n_grid2 - k = k + 1_8 + k = k + 1_size_t rij(1:3,1,k) = final_grid_points (1:3,ipoint) rij(1:3,2,k) = final_grid_points_extra(1:3,jpoint) enddo enddo - rc = qmckl_set_electron_coord(qmckl_ctx_jastrow, 'N', n_points, rij, 6_8*n_points) + rc = qmckl_set_electron_coord(qmckl_ctx_jastrow, 'N', n_points, rij, 6_size_t*n_points) if(rc /= QMCKL_SUCCESS) then print *, irp_here, 'qmckl error in set_electron_coord' rc = qmckl_check(qmckl_ctx_jastrow, rc) stop -1 endif - rc = qmckl_get_jastrow_champ_factor_ee_gl(qmckl_ctx_jastrow, gl, 8_8*n_points) + rc = qmckl_get_jastrow_champ_factor_ee_gl(qmckl_ctx_jastrow, gl, 8_size_t*n_points) if(rc /= QMCKL_SUCCESS) then print *, irp_here, 'qmckl error in fact_ee_gl' rc = qmckl_check(qmckl_ctx_jastrow, rc) stop -1 endif - k = 0_8 + k = 0_size_t do i_grid1 = 1, n_grid1 do jpoint = 1, n_grid2 - k = k + 1_8 + k = k + 1_size_t resx(jpoint,i_grid1) = gl(1,1,k) resy(jpoint,i_grid1) = gl(1,2,k) resz(jpoint,i_grid1) = gl(1,3,k) enddo enddo - rc = qmckl_get_jastrow_champ_factor_een_gl(qmckl_ctx_jastrow, gl, 8_8*n_points) + rc = qmckl_get_jastrow_champ_factor_een_gl(qmckl_ctx_jastrow, gl, 8_size_t*n_points) if(rc /= QMCKL_SUCCESS) then print *, irp_here, 'qmckl error in fact_een_gl' rc = qmckl_check(qmckl_ctx_jastrow, rc) stop -1 endif - k = 0_8 + k = 0_size_t do i_grid1 = 1, n_grid1 do jpoint = 1, n_grid2 - k = k + 1_8 + k = k + 1_size_t resx(jpoint,i_grid1) = resx(jpoint,i_grid1) + gl(1,1,k) resy(jpoint,i_grid1) = resy(jpoint,i_grid1) + gl(1,2,k) resz(jpoint,i_grid1) = resz(jpoint,i_grid1) + gl(1,3,k) enddo enddo - rc = qmckl_get_jastrow_champ_factor_en_gl(qmckl_ctx_jastrow, gl, 8_8*n_points) + rc = qmckl_get_jastrow_champ_factor_en_gl(qmckl_ctx_jastrow, gl, 8_size_t*n_points) if(rc /= QMCKL_SUCCESS) then print *, irp_here, 'qmckl error in fact_en_gl' rc = qmckl_check(qmckl_ctx_jastrow, rc) @@ -236,10 +237,10 @@ subroutine get_grad1_u12_withsq_qmckl_block(ipoint_first, n_grid1, n_grid2, resx endif fac_en = 1.d0 / dble(elec_num - 1) - k = 0_8 + k = 0_size_t do i_grid1 = 1, n_grid1 do jpoint = 1, n_grid2 - k = k + 1_8 + k = k + 1_size_t dx = resx(jpoint,i_grid1) + fac_en * gl(1,1,k) dy = resy(jpoint,i_grid1) + fac_en * gl(1,2,k) dz = resz(jpoint,i_grid1) + fac_en * gl(1,3,k) diff --git a/plugins/local/non_h_ints_mu/tc_integ.irp.f b/plugins/local/non_h_ints_mu/tc_integ.irp.f index 71a0200e..fc77a222 100644 --- a/plugins/local/non_h_ints_mu/tc_integ.irp.f +++ b/plugins/local/non_h_ints_mu/tc_integ.irp.f @@ -1,3 +1,4 @@ +use sizet BEGIN_PROVIDER [double precision, int2_grad1_u12_ao, (ao_num, ao_num, n_points_final_grid, 3)] @@ -10,7 +11,8 @@ END_DOC implicit none - integer :: ipoint, i, j, m, jpoint + integer :: m + integer(size_t) :: ipoint, i, j, jpoint double precision :: time0, time1 double precision :: x, y, z, r2 double precision :: dx, dy, dz @@ -149,7 +151,8 @@ END_DOC implicit none - integer :: ipoint, i, j, m, jpoint + integer :: m + integer(size_t) :: ipoint, i, j, jpoint double precision :: x, y, z, r2 double precision :: dx, dy, dz, dr2 double precision :: dx1, dy1, dz1, dx2, dy2, dz2, dr12 diff --git a/plugins/local/non_h_ints_mu/tc_integ_num.irp.f b/plugins/local/non_h_ints_mu/tc_integ_num.irp.f index 35a337b4..629024ce 100644 --- a/plugins/local/non_h_ints_mu/tc_integ_num.irp.f +++ b/plugins/local/non_h_ints_mu/tc_integ_num.irp.f @@ -1,3 +1,4 @@ +use sizet ! --- @@ -13,9 +14,10 @@ END_DOC implicit none - integer :: ipoint, i, j, m, jpoint - integer :: n_blocks, n_this - integer :: i_blocks, ii + integer :: m + integer(size_t) :: ipoint, i, j, jpoint + integer(size_t) :: n_blocks, n_this + integer(size_t) :: i_blocks, ii double precision :: time0, time1 double precision :: mem, n_double double precision, allocatable :: tmp(:,:,:) @@ -44,16 +46,16 @@ if (j2e_type == 'Qmckl') then ! Bound the number of electron pairs held by the QMCkl context. - n_blocks = min(32, n_points_final_grid) + n_blocks = min(32_size_t, n_points_final_grid) else call total_memory(mem) mem = max(1.d0, qp_max_mem - mem) n_double = mem * 1.d8 - n_blocks = max(1, int(min(n_double / (4.d0 * n_points_extra_final_grid), & - dble(n_points_final_grid)))) + n_blocks = int(max(1.d0, min(n_double / (4.d0 * n_points_extra_final_grid), & + dble(n_points_final_grid))), size_t) endif - call write_int(6, n_blocks, 'Size of the blocks') + call write_int(6, int(n_blocks, 4), 'Size of the blocks') allocate(tmp_grad1_u12(n_points_extra_final_grid,n_blocks,3)) allocate(tmp_grad1_u12_squared(n_points_extra_final_grid,n_blocks)) @@ -77,12 +79,12 @@ ! Use both results before reusing the pair-grid workspace for the next block. do m = 1, 3 - call dgemm('T','N',ao_num*ao_num,n_this,n_points_extra_final_grid,1.d0, & - tmp,n_points_extra_final_grid,tmp_grad1_u12(1,1,m),n_points_extra_final_grid, & + call dgemm('T','N',ao_num*ao_num,int(n_this, 4),int(n_points_extra_final_grid, 4),1.d0, & + tmp,int(n_points_extra_final_grid, 4),tmp_grad1_u12(1,1,m),int(n_points_extra_final_grid, 4), & 0.d0,int2_grad1_u12_ao_num(1,1,ii,m),ao_num*ao_num) enddo - call dgemm('T','N',ao_num*ao_num,n_this,n_points_extra_final_grid,-0.5d0, & - tmp,n_points_extra_final_grid,tmp_grad1_u12_squared,n_points_extra_final_grid, & + call dgemm('T','N',ao_num*ao_num,int(n_this, 4),int(n_points_extra_final_grid, 4),-0.5d0, & + tmp,int(n_points_extra_final_grid, 4),tmp_grad1_u12_squared,int(n_points_extra_final_grid, 4), & 0.d0,int2_grad1_u12_square_ao_num(1,1,ii),ao_num*ao_num) enddo @@ -109,7 +111,8 @@ END_DOC implicit none - integer :: ipoint, i, j, m, jpoint + integer :: m + integer(size_t) :: ipoint, i, j, jpoint double precision :: time0, time1 double precision, allocatable :: tmp(:,:,:) @@ -136,15 +139,19 @@ !$OMP END PARALLEL do m = 1, 3 - call dgemm( "T", "N", ao_num*ao_num, n_points_final_grid, n_points_extra_final_grid, 1.d0 & - , tmp(1,1,1), n_points_extra_final_grid, grad1_u12_num(1,1,m), n_points_extra_final_grid & - , 0.d0, int2_grad1_u12_ao_num_1shot(1,1,1,m), ao_num*ao_num) + call dgemm( "T", "N", ao_num*ao_num, int(n_points_final_grid, 4) & + , int(n_points_extra_final_grid, 4), 1.d0 & + , tmp(1,1,1), int(n_points_extra_final_grid, 4) & + , grad1_u12_num(1,1,m), int(n_points_extra_final_grid, 4) & + , 0.d0, int2_grad1_u12_ao_num_1shot(1,1,1,m), ao_num*ao_num) enddo FREE grad1_u12_num - call dgemm( "T", "N", ao_num*ao_num, n_points_final_grid, n_points_extra_final_grid, -0.5d0 & - , tmp(1,1,1), n_points_extra_final_grid, grad1_u12_squared_num(1,1), n_points_extra_final_grid & - , 0.d0, int2_grad1_u12_square_ao_num_1shot(1,1,1), ao_num*ao_num) + call dgemm( "T", "N", ao_num*ao_num, int(n_points_final_grid, 4) & + , int(n_points_extra_final_grid, 4), -0.5d0 & + , tmp(1,1,1), int(n_points_extra_final_grid, 4) & + , grad1_u12_squared_num(1,1), int(n_points_extra_final_grid, 4) & + , 0.d0, int2_grad1_u12_square_ao_num_1shot(1,1,1), ao_num*ao_num) FREE grad1_u12_squared_num deallocate(tmp) From 69cab559e2889e74e756afdf891a7ebcad890546 Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 21:15:53 +0100 Subject: [PATCH 24/26] tc_scf: re-apply the yyjson logging on top of the ported rh_tcscf_diis.irp.f The dev-stable version of the file (PR #439) still logs with json_unit and json_*_fmt, which qp3 does not have. Re-apply the conversion made in 7340201c to the ported text: same paths, plus the new AO residual value as /results/tc_scf/ao_residual and the DIIS history size as /results/tc_scf/diis_size. No other change to the ported code. --- plugins/local/tc_scf/rh_tcscf_diis.irp.f | 38 ++++++++++-------------- 1 file changed, 16 insertions(+), 22 deletions(-) diff --git a/plugins/local/tc_scf/rh_tcscf_diis.irp.f b/plugins/local/tc_scf/rh_tcscf_diis.irp.f index ca87fec8..fb856f4e 100644 --- a/plugins/local/tc_scf/rh_tcscf_diis.irp.f +++ b/plugins/local/tc_scf/rh_tcscf_diis.irp.f @@ -2,6 +2,7 @@ subroutine rh_tcscf_diis() + use qp_json, only: json_add use diis_history_module implicit none @@ -234,46 +235,39 @@ subroutine rh_tcscf_diis() it, etc_tot, etc_1e, etc_2e, etc_3e, e_delta, er_DIIS, level_shift_tcscf, history_count, (t1-t0)/60.d0 call lock_io - if(it == 1) then - write(json_unit, json_dict_uopen_fmt) - else - write(json_unit, json_dict_close_uopen_fmt) - endif - write(json_unit, json_int_fmt) ' iteration ', it - write(json_unit, json_real_fmt) ' SCF TC Energy ', etc_tot - write(json_unit, json_real_fmt) ' E(1e) ', etc_1e - write(json_unit, json_real_fmt) ' E(2e) ', etc_2e - write(json_unit, json_real_fmt) ' E(3e) ', etc_3e - write(json_unit, json_real_fmt) ' AO residual ', ao_residual - write(json_unit, json_real_fmt) ' delta Energy ', e_delta - write(json_unit, json_real_fmt) ' DIIS error ', er_DIIS - write(json_unit, json_real_fmt) ' level_shift ', level_shift_tcscf - write(json_unit, json_int_fmtx) ' DIIS ', history_count - write(json_unit, json_real_fmt) ' Wall time (min)', (t1-t0)/60.d0 + call json_add('/results/tc_scf/iteration', it) + call json_add('/results/tc_scf/scf_tc_energy', etc_tot) + call json_add('/results/tc_scf/energy_1e', etc_1e) + call json_add('/results/tc_scf/energy_2e', etc_2e) + call json_add('/results/tc_scf/energy_3e', etc_3e) + call json_add('/results/tc_scf/ao_residual', ao_residual) + call json_add('/results/tc_scf/delta_energy', e_delta) + call json_add('/results/tc_scf/diis_error', er_DIIS) + call json_add('/results/tc_scf/level_shift', level_shift_tcscf) + call json_add('/results/tc_scf/diis_size', history_count) + call json_add('/results/tc_scf/wall_time_min', (t1-t0)/60.d0) call unlock_io if(er_delta .lt. 0.d0) then call ezfio_set_tc_scf_tcscf_energy(etc_tot) call ezfio_set_bi_ortho_mos_mo_l_coef(mo_l_coef) call ezfio_set_bi_ortho_mos_mo_r_coef(mo_r_coef) - write(json_unit, json_true_fmt) 'saved' + call json_add('/results/tc_scf/saved', .true.) else - write(json_unit, json_false_fmt) 'saved' + call json_add('/results/tc_scf/saved', .false.) endif call lock_io if(converged) then - write(json_unit, json_true_fmtx) 'converged' + call json_add('/results/tc_scf/converged', .true.) call ezfio_set_tc_scf_converged_tcscf(converged) else - write(json_unit, json_false_fmtx) 'converged' + call json_add('/results/tc_scf/converged', .false.) endif call unlock_io if(qp_stop()) exit enddo - write(json_unit, json_dict_close_fmtx) - if(converged) then print *, ' TCSCF DIIS converged !' else From 2189441182f933cef4d1468d68a4b4fae24e9b3a Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Tue, 1 Dec 2026 22:01:38 +0100 Subject: [PATCH 25/26] tc_scf: pass cholesky_ao_num to dgemm through a 32-bit temporary (pre-existing, from #437) The Cholesky rank became integer(size_t) in #437, but it is passed to the interface-less dgemm at ten argument positions, and gfortran then infers the dummy kind from whichever call it saw first: it warns 'Type mismatch (INTEGER(8)/INTEGER(4))' and reads 32 bits of a 64-bit actual. Introduce the conventions.rst idiom, a cholesky_ao_num_4 boundary temporary per subroutine, and use it at every dgemm position; array bounds and loop limits keep the size_t value. --- plugins/local/tc_scf/fock_tc_core.irp.f | 32 ++++++++++++++----------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/plugins/local/tc_scf/fock_tc_core.irp.f b/plugins/local/tc_scf/fock_tc_core.irp.f index 4f411ce6..055887af 100644 --- a/plugins/local/tc_scf/fock_tc_core.irp.f +++ b/plugins/local/tc_scf/fock_tc_core.irp.f @@ -140,22 +140,24 @@ END_DOC integer :: m,n,l,s,j + integer :: cholesky_ao_num_4 double precision :: integral double precision, allocatable :: X(:), X2(:,:,:,:), X3(:,:,:,:) allocate (X(cholesky_ao_num)) + cholesky_ao_num_4 = int(cholesky_ao_num, 4) ! X(j) = \sum_{mn} TCSCF_bi_ort_core_dm_ao(m,n) * cholesky_ao(m,n,j) - call dgemm('T','N',cholesky_ao_num,1,ao_num*ao_num,1.d0, & + call dgemm('T','N',cholesky_ao_num_4,1,ao_num*ao_num,1.d0, & cholesky_ao, ao_num*ao_num, & TCSCF_bi_ort_core_dm_ao, ao_num*ao_num,0.d0, & - X, cholesky_ao_num) + X, cholesky_ao_num_4) ! ! ao_two_e_core_integral_chol(m,n) = \sum_{j} cholesky_ao(m,n,j) * X(j) - call dgemm('N','N',ao_num*ao_num,1,cholesky_ao_num, 1.d0, & + call dgemm('N','N',ao_num*ao_num,1,cholesky_ao_num_4, 1.d0, & cholesky_ao, ao_num*ao_num, & - X, cholesky_ao_num, 0.d0, & + X, cholesky_ao_num_4, 0.d0, & ao_two_e_core_integral_chol, ao_num*ao_num) deallocate(X) @@ -186,7 +188,7 @@ do iblock=1,cholesky_ao_num,block_size - call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size),ao_num, 1.d0, & + call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size),ao_num, 1.d0, & TCSCF_bi_ort_core_dm_ao, ao_num, & cholesky_ao(1,1,iblock), ao_num, 0.d0, & X2(1,1,1,1), ao_num) @@ -199,7 +201,7 @@ enddo enddo - call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size), -1.d0, & + call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size), -1.d0, & cholesky_ao(1,1,iblock), ao_num, & X3(1,1,1,1), ao_num*block_size, 1.d0, & ao_two_e_core_integral_chol, ao_num) @@ -220,22 +222,24 @@ END_DOC integer :: m,n,l,s,j + integer :: cholesky_ao_num_4 double precision :: integral double precision, allocatable :: X(:), X2(:,:,:,:), X3(:,:,:,:) allocate (X(cholesky_ao_num)) + cholesky_ao_num_4 = int(cholesky_ao_num, 4) ! X(j) = \sum_{mn} SCF_density_matrix_ao(m,n) * cholesky_ao(m,n,j) - call dgemm('T','N',cholesky_ao_num,1,ao_num*ao_num,1.d0, & + call dgemm('T','N',cholesky_ao_num_4,1,ao_num*ao_num,1.d0, & cholesky_ao, ao_num*ao_num, & TCSCF_bi_ort_valence_dm_ao_full, ao_num*ao_num,0.d0, & - X, cholesky_ao_num) + X, cholesky_ao_num_4) ! ! ao_two_e_integral_alpha(m,n) = \sum_{j} cholesky_ao(m,n,j) * X(j) - call dgemm('N','N',ao_num*ao_num,1,cholesky_ao_num, 1.d0, & + call dgemm('N','N',ao_num*ao_num,1,cholesky_ao_num_4, 1.d0, & cholesky_ao, ao_num*ao_num, & - X, cholesky_ao_num, 0.d0, & + X, cholesky_ao_num_4, 0.d0, & ao_two_e_valence_integral_alpha_chol, ao_num*ao_num) deallocate(X) @@ -271,13 +275,13 @@ do iblock=1,cholesky_ao_num,block_size - call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size),ao_num, 1.d0, & + call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size),ao_num, 1.d0, & TCSCF_bi_ort_valence_dm_ao_alpha, ao_num, & cholesky_ao(1,1,iblock), ao_num, 0.d0, & X2(1,1,1,1), ao_num) if (elec_alpha_num > elec_beta_num) then - call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size),ao_num, 1.d0, & + call dgemm('N','N',ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size),ao_num, 1.d0, & TCSCF_bi_ort_valence_dm_ao_beta, ao_num, & cholesky_ao(1,1,iblock), ao_num, 0.d0, & X2(1,1,1,2), ao_num) @@ -302,13 +306,13 @@ enddo endif - call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size), -1.d0, & + call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size), -1.d0, & cholesky_ao(1,1,iblock), ao_num, & X3(1,1,1,1), ao_num*block_size, 1.d0, & ao_two_e_valence_integral_alpha_chol, ao_num) if (elec_alpha_num > elec_beta_num) then - call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num-iblock+1,block_size), -1.d0, & + call dgemm('N','N',ao_num,ao_num,ao_num*min(cholesky_ao_num_4-iblock+1,block_size), -1.d0, & cholesky_ao(1,1,iblock), ao_num, & X3(1,1,1,2), ao_num*block_size, 1.d0, & ao_two_e_valence_integral_beta_chol, ao_num) From c38c29bc0d170996348fda879e81057f58a6181c Mon Sep 17 00:00:00 2001 From: Anthony Scemama Date: Wed, 2 Dec 2026 02:28:21 +0100 Subject: [PATCH 26/26] ci: compile the plugin layer The plugins are not in the default build and no workflow installs them, so a plugin module can stay uncompilable for months: between the size_t conversion (#437) and the yyjson rewrite (5a721280) the TC closure accumulated ten defects -- all fixed earlier in this branch -- and nothing would have reported any of them. ci/plugins.txt lists what to build; `qp plugins install` resolves each name's NEED closure (three names, twelve modules), and growing coverage later is one line per plugin. The new workflow builds the core, installs and compiles the closure on a cold tree, then fails on any "Type mismatch" warning -- integer kinds across a call boundary are silent value corruption and no build gate sees them -- and runs the two tc_scf unit tests plus diis_history_qp_test. It is limited to qp3, where json_init/json_add exist. The build step is a keep-going cascade, measured rather than guessed: IRPF90's per-module graph declares no .mod outputs, and one program stub edge has no dependency that builds the sizet.mod it reads, so a cold module can compile the stub first. A serial retry cannot fix that (ninja runs independent edges in graph order even at -j1, so it fails the same way every run), and the wrapper's "Compiling all modules" edge is itself a sub-ninja that does not inherit -k 0. `-k 0` at the wrapper, `-k 0` on config/build.ninja, two keep-going passes per inner graph and a plain ninja as the real gate make the cold build deterministic without touching the generated graphs; it was proven from a fully cleaned plugin tree. TODO: fix the IRPF90 stub edge, then delete the cascade. --- .github/workflows/plugins.yml | 140 ++++++++++++++++++++++++++++++++++ ci/plugins.txt | 16 ++++ 2 files changed, 156 insertions(+) create mode 100644 .github/workflows/plugins.yml create mode 100644 ci/plugins.txt diff --git a/.github/workflows/plugins.yml b/.github/workflows/plugins.yml new file mode 100644 index 00000000..9d716342 --- /dev/null +++ b/.github/workflows/plugins.yml @@ -0,0 +1,140 @@ +# Compile the plugin layer. +# +# The plugins are not part of the default build and no other workflow installs +# them, so a plugin module can stay uncompilable for months: between the size_t +# conversion (PR #437) and the yyjson rewrite (5a721280) the TC closure +# accumulated ten defects that only surfaced when someone built it by hand +# (2026-12-01, PR #440). This job is what would have caught the first of them. +# +# The list lives in ci/plugins.txt; `qp plugins install` resolves the NEED +# closure, so the file lists leaves, not every module. +name: QP Plugins + +on: + push: + branches: + - qp3 + pull_request: + branches: + - qp3 + workflow_dispatch: + +concurrency: + group: plugins-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + + plugins: + name: Compilation (plugins) + runs-on: ubuntu-24.04 + timeout-minutes: 60 + + steps: + - uses: actions/checkout@v3 + + - name: Restore dependency cache + uses: actions/cache@v3 + with: + key: qp2-config + fail-on-cache-miss: false + path: | + include/ + lib/ + lib64/ + libexec/ + restore-keys: qp2- + + - name: Install dependencies + run: | + sudo apt update + sudo apt install -y --fix-missing --no-install-recommends \ + gfortran gcc liblapack-dev libblas-dev wget python3 make m4 pkg-config + + - name: Install Rust toolchain + run: rustup toolchain install 1.92.0 --profile minimal --component rustfmt,clippy + + - name: Configuration + run: | + # Same recipe as the Compilation job: the cache is an + # optimization, every package is installed explicitly, so a cache + # miss only costs time. configure also initializes the submodules + # (git submodule update --init --recursive). + if ! ls lib/libz.* >/dev/null 2>&1; then + ./configure -i zlib || : + fi + ./configure -i ninja || : + ./configure -i docopt || : + ./configure -i resultsFile || : + ./configure -i bats || : + ./configure -i trexio-nohdf5 || : + ./configure -i qmckl || : + ./configure -i simple_gpu || : + ./configure -i libcint || : + ./configure -c ./config/gfortran_debug.cfg -b ninja + + - name: Core compilation + run: bash -c "source quantum_package.rc ; exec ninja" + + - name: Install the plugins listed in ci/plugins.txt + run: | + source quantum_package.rc + # Several names in one call; it installs the NEED closure and + # runs `qp_create_ninja update` (graph + EZFIO interfaces). + qp plugins install $(grep -v '^#' ci/plugins.txt | tr '\n' ' ') + echo "installed: $(qp plugins list -i | tr '\n' ' ')" + + - name: Compile the plugin closure + run: | + source quantum_package.rc + set -o pipefail + # Cold-tree race, rehearsed 2026-12-01: IRPF90's per-module graph + # declares no .mod outputs, and one program stub edge has no + # dependency that would build the sizet.mod it reads, so a cold + # module can compile the stub before sizet.f90. A serial retry + # cannot fix it (ninja runs independent edges in graph order even + # at -j1, and a parallel re-run is a fresh coin flip). + # Keep going instead: -k 0 builds every other edge of the module, + # so the .mod producers are done before the pass that compiles the + # stub. The wrapper's "Compiling all modules" edge is itself a + # sub-ninja that does not inherit -k 0, hence the direct call. + # TODO: fix the IRPF90 stub edge and delete this cascade. + ninja -k 0 2>&1 | tee -a plugin-build.log || true + ninja -f config/build.ninja -k 0 2>&1 | tee -a plugin-build.log || true + for dir in src/*/IRPF90_temp ; do + ( cd "$dir" && ninja -k 0 ; ninja -k 0 ) >>plugin-build.log 2>&1 || true + done + ninja 2>&1 | tee -a plugin-build.log + + - name: No integer-kind mismatch at a call boundary + # gfortran only warns on an INTEGER(8)/INTEGER(4) mismatch across a call + # boundary (implicit interface) and silently reads 32 bits of a 64-bit + # actual. The conventions forbid the mix, so make the warning fatal for + # the code this job compiles. + run: | + if grep -n -i "type mismatch" plugin-build.log ; then + echo "::error::integer kind mismatch across a call boundary" + exit 1 + fi + + - name: Unit tests (tc_scf) + run: | + source quantum_package.rc + cd plugins/local/tc_scf/tests + ninja # builds test_diis_history (its build.ninja default) + ./test_diis_history + # tests/build.ninja has no target for the biorthogonal test + # (upstream gap): compile it here instead of editing a ported file. + gfortran -O0 -g -fcheck=all -I. -J. -c ../biorthogonal_scaling.f90 -o biorthogonal_scaling.o + gfortran -O0 -g -fcheck=all -I. -J. test_biorthogonal_scaling.f90 \ + biorthogonal_scaling.o -llapack -lblas -o test_biorthogonal_scaling + ./test_biorthogonal_scaling + cd "$QP_ROOT" + ./src/tc_scf/diis_history_qp_test # IRPF90-level integration of the same module + + - name: Report the first errors on failure + if: failure() + run: | + git status --porcelain | head -40 + echo + grep -n -E "Error:|error:|FAILED:" plugin-build.log | head -40 || true diff --git a/ci/plugins.txt b/ci/plugins.txt new file mode 100644 index 00000000..71e8a689 --- /dev/null +++ b/ci/plugins.txt @@ -0,0 +1,16 @@ +# Plugins built by .github/workflows/plugins.yml. +# +# `qp plugins install` resolves each name's NEED closure, so listing the leaves +# is enough: tc_scf non_h_ints_mu non_hermit_dav => 12 modules today +# (ao_many_one_e_ints ao_tc_eff_map bi_ort_ints bi_ortho_mos jastrow +# non_h_ints_mu non_hermit_dav ortho_three_e_ints qmckl spher_harm +# tc_keywords tc_scf). +# +# Grow this list toward every directory in plugins/local as the remaining +# breakage is fixed. Today these two still write through the JSON API deleted +# in 5a721280, so they are not listed: +# plugins/local/fci_tc_bi/fci_tc_bi_ortho.irp.f +# plugins/local/cipsi_tc_bi_ortho/write_cipsi_json.irp.f +tc_scf +non_h_ints_mu +non_hermit_dav