LCOV - code coverage report
Current view: top level - src/dbt - dbt_methods.F (source / functions) Coverage Total Hit
Test: CP2K Regtests (git:1be8651) Lines: 94.5 % 1004 949
Test Date: 2026-11-24 01:22:08 Functions: 96.9 % 32 31

            Line data    Source code
       1              : !--------------------------------------------------------------------------------------------------!
       2              : !   CP2K: A general program to perform molecular dynamics simulations                              !
       3              : !   Copyright 2000-2026 CP2K developers group <https://cp2k.org>                                   !
       4              : !                                                                                                  !
       5              : !   SPDX-License-Identifier: GPL-2.0-or-later                                                      !
       6              : !--------------------------------------------------------------------------------------------------!
       7              : 
       8              : ! **************************************************************************************************
       9              : !> \brief DBT tensor framework for block-sparse tensor contraction.
      10              : !>        Representation of n-rank tensors as DBT tall-and-skinny matrices.
      11              : !>        Support for arbitrary redistribution between different representations.
      12              : !>        Support for arbitrary tensor contractions
      13              : !> \todo implement checks and error messages
      14              : !> \author Patrick Seewald
      15              : ! **************************************************************************************************
      16              : MODULE dbt_methods
      17              :    #:include "dbt_macros.fypp"
      18              :    #:set maxdim = maxrank
      19              :    #:set ndims = range(2,maxdim+1)
      20              : 
      21              :    USE cp_dbcsr_api, ONLY: &
      22              :       dbcsr_type, dbcsr_release, &
      23              :       dbcsr_iterator_type, dbcsr_iterator_start, dbcsr_iterator_blocks_left, dbcsr_iterator_next_block, &
      24              :       dbcsr_has_symmetry, dbcsr_desymmetrize, dbcsr_put_block, dbcsr_clear, dbcsr_iterator_stop
      25              :    USE dbt_allocate_wrap, ONLY: &
      26              :       allocate_any
      27              :    USE dbt_array_list_methods, ONLY: &
      28              :       get_arrays, reorder_arrays, get_ith_array, array_list, array_sublist, check_equal, array_eq_i, &
      29              :       create_array_list, destroy_array_list, sizes_of_arrays
      30              :    USE dbm_api, ONLY: &
      31              :       dbm_clear
      32              :    USE dbt_tas_types, ONLY: &
      33              :       dbt_tas_split_info
      34              :    USE dbt_tas_base, ONLY: &
      35              :       dbt_tas_copy, dbt_tas_finalize, dbt_tas_get_info, dbt_tas_info
      36              :    USE dbt_tas_mm, ONLY: &
      37              :       dbt_tas_multiply, dbt_tas_batched_mm_init, dbt_tas_batched_mm_finalize, &
      38              :       dbt_tas_batched_mm_complete, dbt_tas_set_batched_state
      39              :    USE dbt_block, ONLY: &
      40              :       dbt_iterator_type, dbt_get_block, dbt_put_block, dbt_iterator_start, &
      41              :       dbt_iterator_blocks_left, dbt_iterator_stop, dbt_iterator_next_block, &
      42              :       ndims_iterator, dbt_reserve_blocks, block_nd, destroy_block, checker_tr
      43              :    USE dbt_index, ONLY: &
      44              :       dbt_get_mapping_info, nd_to_2d_mapping, dbt_inverse_order, permute_index, get_nd_indices_tensor, &
      45              :       ndims_mapping_row, ndims_mapping_column, ndims_mapping
      46              :    USE dbt_types, ONLY: &
      47              :       dbt_create, dbt_type, ndims_tensor, dims_tensor, &
      48              :       dbt_distribution_type, dbt_distribution, dbt_nd_mp_comm, dbt_destroy, &
      49              :       dbt_distribution_destroy, dbt_distribution_new_expert, dbt_get_stored_coordinates, &
      50              :       blk_dims_tensor, dbt_hold, dbt_pgrid_type, mp_environ_pgrid, dbt_filter, &
      51              :       dbt_clear, dbt_finalize, dbt_get_num_blocks, dbt_scale, &
      52              :       dbt_get_num_blocks_total, dbt_get_info, ndims_matrix_row, ndims_matrix_column, &
      53              :       dbt_max_nblks_local, dbt_default_distvec, dbt_contraction_storage, dbt_nblks_total, &
      54              :       dbt_distribution_new, dbt_copy_contraction_storage, dbt_pgrid_destroy, dbt_get_nze
      55              :    USE kinds, ONLY: &
      56              :       dp, default_string_length, int_8, dp
      57              :    USE message_passing, ONLY: &
      58              :       mp_cart_type
      59              :    USE util, ONLY: &
      60              :       sort
      61              :    USE dbt_reshape_ops, ONLY: &
      62              :       dbt_reshape, dbt_reshape_release
      63              :    USE dbt_tas_split, ONLY: &
      64              :       dbt_tas_mp_comm, rowsplit, colsplit, dbt_tas_info_hold, dbt_tas_release_info, default_nsplit_accept_ratio, &
      65              :       default_pdims_accept_ratio, dbt_tas_create_split
      66              :    USE dbt_split, ONLY: &
      67              :       dbt_split_copyback, dbt_make_compatible_blocks, dbt_crop
      68              :    USE dbt_io, ONLY: &
      69              :       dbt_write_tensor_info, dbt_write_tensor_dist, prep_output_unit, dbt_write_split_info
      70              :    USE message_passing, ONLY: mp_comm_type
      71              : 
      72              : #include "../base/base_uses.f90"
      73              : 
      74              :    IMPLICIT NONE
      75              :    PRIVATE
      76              :    CHARACTER(len=*), PARAMETER, PRIVATE :: moduleN = 'dbt_methods'
      77              : 
      78              :    PUBLIC :: &
      79              :       dbt_contract, &
      80              :       dbt_copy, &
      81              :       dbt_get_block, &
      82              :       dbt_get_stored_coordinates, &
      83              :       dbt_inverse_order, &
      84              :       dbt_iterator_blocks_left, &
      85              :       dbt_iterator_next_block, &
      86              :       dbt_iterator_start, &
      87              :       dbt_iterator_stop, &
      88              :       dbt_iterator_type, &
      89              :       dbt_put_block, &
      90              :       dbt_reserve_blocks, &
      91              :       dbt_copy_matrix_to_tensor, &
      92              :       dbt_copy_tensor_to_matrix, &
      93              :       dbt_batched_contract_init, &
      94              :       dbt_batched_contract_finalize, &
      95              :       dbt_library_init, &
      96              :       dbt_library_finalize, &
      97              :       dbt_library_print_stats, &
      98              :       dbt_clear_mempools
      99              : 
     100              :    ! Per contraction (tensor names): remapped and cropped tensors, i.e., data copied
     101              :    ! before the multiplication (local to the rank)
     102              :    TYPE contract_stats_type
     103              :       CHARACTER(LEN=3*default_string_length + 6)  :: names = ""
     104              :       INTEGER(KIND=int_8)                         :: ncalls = 0, nempty = 0, flop = 0
     105              :       INTEGER(KIND=int_8), DIMENSION(3)           :: nremap = 0, nzremap = 0
     106              :       INTEGER(KIND=int_8), DIMENSION(2)           :: ncrop = 0, nzcrop = 0, ncrop_remap = 0
     107              :    END TYPE contract_stats_type
     108              : 
     109              :    TYPE(contract_stats_type), DIMENSION(:), ALLOCATABLE, SAVE :: contract_stats
     110              :    INTEGER, SAVE                                               :: ncontract_stats = 0
     111              : 
     112              : CONTAINS
     113              : 
     114              : ! **************************************************************************************************
     115              : !> \brief Initialize the DBT library (after dbm_library_init).
     116              : !> \author Hans Pabst
     117              : ! **************************************************************************************************
     118         1494 :    SUBROUTINE dbt_library_init()
     119         1494 :    END SUBROUTINE dbt_library_init
     120              : 
     121              : ! **************************************************************************************************
     122              : !> \brief Finalize the DBT library (before dbm_library_finalize), which releases its buffers.
     123              : !> \author Hans Pabst
     124              : ! **************************************************************************************************
     125         1494 :    SUBROUTINE dbt_library_finalize()
     126         1494 :       CALL dbt_clear_mempools()
     127         1494 :       IF (ALLOCATED(contract_stats)) DEALLOCATE (contract_stats)
     128         1494 :       ncontract_stats = 0
     129         1494 :    END SUBROUTINE dbt_library_finalize
     130              : 
     131              : ! **************************************************************************************************
     132              : !> \brief Release the buffers that persist across calls (as dbcsr_clear_mempools), e.g., once a
     133              : !>        phase with large tensor operations ends. They are allocated again when needed.
     134              : !> \author Hans Pabst
     135              : ! **************************************************************************************************
     136         2934 :    SUBROUTINE dbt_clear_mempools()
     137         2934 :       CALL dbt_reshape_release()
     138         2934 :    END SUBROUTINE dbt_clear_mempools
     139              : 
     140              : ! **************************************************************************************************
     141              : !> \brief Print per-contraction statistics (rank-local table, totals over all ranks).
     142              : !> \param mpi_comm communicator of all ranks calling this routine
     143              : !> \param output_unit unit to write to (rank-local table is written if positive)
     144              : !> \author Hans Pabst
     145              : ! **************************************************************************************************
     146        11422 :    SUBROUTINE dbt_library_print_stats(mpi_comm, output_unit)
     147              :       TYPE(mp_comm_type), INTENT(IN)                     :: mpi_comm
     148              :       INTEGER, INTENT(IN)                                :: output_unit
     149              : 
     150              :       INTEGER                                            :: i, j, k
     151              :       INTEGER(KIND=int_8)                                :: ncalls, nzcopied
     152        11422 :       INTEGER, DIMENSION(:), ALLOCATABLE                 :: order
     153        11422 :       REAL(KIND=dp), DIMENSION(:), ALLOCATABLE           :: copied
     154              : 
     155        11422 :       ncalls = 0
     156        11422 :       nzcopied = 0
     157        14560 :       DO i = 1, ncontract_stats
     158         3138 :          ncalls = ncalls + contract_stats(i)%ncalls
     159        30250 :          nzcopied = nzcopied + SUM(contract_stats(i)%nzremap) + SUM(contract_stats(i)%nzcrop)
     160              :       END DO
     161        11422 :       CALL mpi_comm%sum(ncalls)
     162        11422 :       CALL mpi_comm%sum(nzcopied)
     163              : 
     164        11422 :       IF (output_unit > 0 .AND. 0 < ncalls) THEN
     165         1335 :          ALLOCATE (order(ncontract_stats), copied(ncontract_stats))
     166         1836 :          DO i = 1, ncontract_stats
     167         1569 :             order(i) = i
     168         9681 :             copied(i) = -REAL(SUM(contract_stats(i)%nzremap) + SUM(contract_stats(i)%nzcrop), dp)
     169              :          END DO
     170          267 :          CALL sort(copied, ncontract_stats, order) ! ascending: most copied data first
     171          267 :          WRITE (output_unit, '(/,T2,A)') REPEAT("-", 79)
     172          267 :          WRITE (output_unit, '(T2,A,T70,A)') "DBT CONTRACTION STATISTICS (rank-local)", "copied [MB]"
     173              :          WRITE (output_unit, '(T2,A,T47,A,T55,A,T62,A,T68,A,T75,A)') &
     174          267 :             "A x B = C", "calls", "remap", "crop", "both", "total"
     175         1836 :          DO k = 1, ncontract_stats
     176         1569 :             i = order(k)
     177          267 :             ASSOCIATE (s => contract_stats(i))
     178              :                WRITE (output_unit, '(T2,A,T44,I8,T52,3I3,T61,2I3,T67,2I3,T73,F8.1)') &
     179         1569 :                   s%names(1:MIN(LEN_TRIM(s%names), 41)), s%ncalls, &
     180        12552 :                   (MIN(s%nremap(j), 99_int_8), j=1, 3), (MIN(s%ncrop(j), 99_int_8), j=1, 2), &
     181         4707 :                   (MIN(s%ncrop_remap(j), 99_int_8), j=1, 2), &
     182        26673 :                   8.0_dp*REAL(SUM(s%nzremap) + SUM(s%nzcrop), dp)/1.0E6_dp
     183              :             END ASSOCIATE
     184              :          END DO
     185          267 :          WRITE (output_unit, '(T2,A,T44,I8,T73,F8.1)') "all ranks", ncalls, 8.0_dp*REAL(nzcopied, dp)/1.0E6_dp
     186          267 :          WRITE (output_unit, '(T2,A)') REPEAT("-", 79)
     187              :       END IF
     188        11422 :    END SUBROUTINE dbt_library_print_stats
     189              : 
     190              : ! **************************************************************************************************
     191              : !> \brief Index of the statistics entry for the given tensor names (created if missing).
     192              : !> \author Hans Pabst
     193              : ! **************************************************************************************************
     194       292855 :    FUNCTION contract_stats_index(name_1, name_2, name_3) RESULT(idx)
     195              :       CHARACTER(LEN=*), INTENT(IN)                       :: name_1, name_2, name_3
     196              :       INTEGER                                            :: idx
     197              : 
     198              :       CHARACTER(LEN=3*default_string_length + 6)         :: names
     199              :       INTEGER                                            :: i
     200       292855 :       TYPE(contract_stats_type), DIMENSION(:), ALLOCATABLE :: grown
     201              : 
     202       292855 :       names = TRIM(name_1)//" x "//TRIM(name_2)//" = "//TRIM(name_3)
     203       292855 :       idx = 0
     204      1483554 :       DO i = 1, ncontract_stats
     205      1483030 :          IF (contract_stats(i)%names == names) idx = i
     206      1483554 :          IF (0 < idx) EXIT
     207              :       END DO
     208       292855 :       IF (0 == idx) THEN
     209         3156 :          IF (.NOT. ALLOCATED(contract_stats)) ALLOCATE (contract_stats(16))
     210          524 :          IF (SIZE(contract_stats) <= ncontract_stats) THEN
     211            0 :             ALLOCATE (grown(2*SIZE(contract_stats)))
     212            0 :             grown(1:ncontract_stats) = contract_stats(1:ncontract_stats)
     213            0 :             CALL MOVE_ALLOC(grown, contract_stats)
     214              :          END IF
     215          524 :          ncontract_stats = ncontract_stats + 1
     216          524 :          idx = ncontract_stats
     217          524 :          contract_stats(idx)%names = names
     218              :       END IF
     219       292855 :    END FUNCTION contract_stats_index
     220              : 
     221              : ! **************************************************************************************************
     222              : !> \brief Copy tensor data.
     223              : !>        Redistributes tensor data according to distributions of target and source tensor.
     224              : !>        Permutes tensor index according to `order` argument (if present).
     225              : !>        Source and target tensor formats are arbitrary as long as the following requirements are met:
     226              : !>        * source and target tensors have the same rank and the same sizes in each dimension in terms
     227              : !>          of tensor elements (block sizes don't need to be the same).
     228              : !>          If `order` argument is present, sizes must match after index permutation.
     229              : !>        OR
     230              : !>        * target tensor is not yet created, in this case an exact copy of source tensor is returned.
     231              : !> \param tensor_in Source
     232              : !> \param tensor_out Target
     233              : !> \param order Permutation of target tensor index.
     234              : !>              Exact same convention as order argument of RESHAPE intrinsic.
     235              : !> \param bounds crop tensor data: start and end index for each tensor dimension
     236              : !> \author Patrick Seewald
     237              : ! **************************************************************************************************
     238       669816 :    SUBROUTINE dbt_copy(tensor_in, tensor_out, order, summation, bounds, move_data, unit_nr)
     239              :       TYPE(dbt_type), INTENT(INOUT), TARGET      :: tensor_in, tensor_out
     240              :       INTEGER, DIMENSION(ndims_tensor(tensor_in)), &
     241              :          INTENT(IN), OPTIONAL                        :: order
     242              :       LOGICAL, INTENT(IN), OPTIONAL                  :: summation, move_data
     243              :       INTEGER, DIMENSION(2, ndims_tensor(tensor_in)), &
     244              :          INTENT(IN), OPTIONAL                        :: bounds
     245              :       INTEGER, INTENT(IN), OPTIONAL                  :: unit_nr
     246              :       INTEGER :: handle
     247              : 
     248       669816 :       CALL timeset("dbt_total", handle)
     249              : 
     250              :       ! make sure that it is safe to use dbt_copy during a batched contraction
     251       669816 :       CALL dbt_tas_batched_mm_complete(tensor_in%matrix_rep, warn=.TRUE.)
     252       669816 :       CALL dbt_tas_batched_mm_complete(tensor_out%matrix_rep, warn=.TRUE.)
     253              : 
     254       669816 :       CALL dbt_copy_expert(tensor_in, tensor_out, order, summation, bounds, move_data, unit_nr)
     255       669816 :       CALL timestop(handle)
     256       669816 :    END SUBROUTINE dbt_copy
     257              : 
     258              : ! **************************************************************************************************
     259              : !> \brief expert routine for copying a tensor. For internal use only.
     260              : !> \author Patrick Seewald
     261              : ! **************************************************************************************************
     262         5772 :    SUBROUTINE dbt_copy_expert(tensor_in, tensor_out, order, summation, bounds, move_data, unit_nr)
     263              :       TYPE(dbt_type), INTENT(INOUT), TARGET      :: tensor_in, tensor_out
     264              :       INTEGER, DIMENSION(ndims_tensor(tensor_in)), &
     265              :          INTENT(IN), OPTIONAL                        :: order
     266              :       LOGICAL, INTENT(IN), OPTIONAL                  :: summation, move_data
     267              :       INTEGER, DIMENSION(2, ndims_tensor(tensor_in)), &
     268              :          INTENT(IN), OPTIONAL                        :: bounds
     269              :       INTEGER, INTENT(IN), OPTIONAL                  :: unit_nr
     270              : 
     271              :       TYPE(dbt_type), POINTER                    :: in_tmp_1, in_tmp_2, &
     272              :                                                     in_tmp_3, out_tmp_1
     273              :       INTEGER                                        :: handle, unit_nr_prv
     274       728681 :       INTEGER, DIMENSION(:), ALLOCATABLE             :: map1_in_1, map1_in_2, map2_in_1, map2_in_2
     275              : 
     276              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'dbt_copy'
     277              :       LOGICAL                                        :: dist_compatible_tas, dist_compatible_tensor, &
     278              :                                                         summation_prv, new_in_1, new_in_2, &
     279              :                                                         new_in_3, new_out_1, block_compatible, &
     280              :                                                         move_prv, crop_reshape
     281       728681 :       TYPE(array_list)                               :: blk_sizes_in
     282              : 
     283       728681 :       CALL timeset(routineN, handle)
     284              : 
     285       728681 :       CPASSERT(tensor_out%valid)
     286              : 
     287       728681 :       unit_nr_prv = prep_output_unit(unit_nr)
     288              : 
     289       728681 :       IF (PRESENT(move_data)) THEN
     290       510005 :          move_prv = move_data
     291              :       ELSE
     292       218676 :          move_prv = .FALSE.
     293              :       END IF
     294              : 
     295       728681 :       dist_compatible_tas = .FALSE.
     296       728681 :       dist_compatible_tensor = .FALSE.
     297       728681 :       block_compatible = .FALSE.
     298       728681 :       new_in_1 = .FALSE.
     299       728681 :       new_in_2 = .FALSE.
     300       728681 :       new_in_3 = .FALSE.
     301       728681 :       new_out_1 = .FALSE.
     302              : 
     303       728681 :       IF (PRESENT(summation)) THEN
     304       212909 :          summation_prv = summation
     305              :       ELSE
     306              :          summation_prv = .FALSE.
     307              :       END IF
     308              : 
     309              :       ! crop while reshaping (single copy) if that is the copy anyway
     310       728681 :       crop_reshape = .FALSE.
     311       728681 :       IF (PRESENT(bounds) .AND. .NOT. PRESENT(order)) crop_reshape = copy_reshapes(tensor_in, tensor_out)
     312       728681 :       IF (PRESENT(bounds) .AND. .NOT. crop_reshape) THEN
     313        33838 :          ALLOCATE (in_tmp_1)
     314         4834 :          CALL dbt_crop(tensor_in, in_tmp_1, bounds=bounds, move_data=move_prv)
     315         4834 :          new_in_1 = .TRUE.
     316         4834 :          move_prv = .TRUE.
     317              :       ELSE
     318              :          in_tmp_1 => tensor_in
     319              :       END IF
     320              : 
     321       728681 :       IF (PRESENT(order)) THEN
     322       208642 :          CALL reorder_arrays(in_tmp_1%blk_sizes, blk_sizes_in, order=order)
     323       208642 :          block_compatible = check_equal(blk_sizes_in, tensor_out%blk_sizes)
     324              :       ELSE
     325       520039 :          block_compatible = check_equal(in_tmp_1%blk_sizes, tensor_out%blk_sizes)
     326              :       END IF
     327              : 
     328       728681 :       IF (.NOT. block_compatible) THEN
     329      1251185 :          ALLOCATE (in_tmp_2, out_tmp_1)
     330              :          CALL dbt_make_compatible_blocks(in_tmp_1, tensor_out, in_tmp_2, out_tmp_1, order=order, &
     331        96245 :                                          nodata2=.NOT. summation_prv, move_data=move_prv)
     332        96245 :          new_in_2 = .TRUE.; new_out_1 = .TRUE.
     333        96245 :          move_prv = .TRUE.
     334              :       ELSE
     335              :          in_tmp_2 => in_tmp_1
     336              :          out_tmp_1 => tensor_out
     337              :       END IF
     338              : 
     339       728681 :       IF (PRESENT(order)) THEN
     340      1460494 :          ALLOCATE (in_tmp_3)
     341       208642 :          CALL dbt_permute_index(in_tmp_2, in_tmp_3, order)
     342       208642 :          new_in_3 = .TRUE.
     343              :       ELSE
     344              :          in_tmp_3 => in_tmp_2
     345              :       END IF
     346              : 
     347      2186043 :       ALLOCATE (map1_in_1(ndims_matrix_row(in_tmp_3)))
     348      2186043 :       ALLOCATE (map1_in_2(ndims_matrix_column(in_tmp_3)))
     349       728681 :       CALL dbt_get_mapping_info(in_tmp_3%nd_index, map1_2d=map1_in_1, map2_2d=map1_in_2)
     350              : 
     351      2186043 :       ALLOCATE (map2_in_1(ndims_matrix_row(out_tmp_1)))
     352      2186043 :       ALLOCATE (map2_in_2(ndims_matrix_column(out_tmp_1)))
     353       728681 :       CALL dbt_get_mapping_info(out_tmp_1%nd_index, map1_2d=map2_in_1, map2_2d=map2_in_2)
     354              : 
     355       728681 :       IF (.NOT. PRESENT(order)) THEN
     356       520039 :          IF (array_eq_i(map1_in_1, map2_in_1) .AND. array_eq_i(map1_in_2, map2_in_2)) THEN
     357       438992 :             dist_compatible_tas = check_equal(in_tmp_3%nd_dist, out_tmp_1%nd_dist)
     358      1053419 :          ELSE IF (array_eq_i([map1_in_1, map1_in_2], [map2_in_1, map2_in_2])) THEN
     359        34554 :             dist_compatible_tensor = check_equal(in_tmp_3%nd_dist, out_tmp_1%nd_dist)
     360              :          END IF
     361              :       END IF
     362              : 
     363       438992 :       IF (dist_compatible_tas) THEN
     364       355082 :          CALL dbt_tas_copy(out_tmp_1%matrix_rep, in_tmp_3%matrix_rep, summation)
     365       355082 :          IF (move_prv) CALL dbt_clear(in_tmp_3)
     366       373599 :       ELSE IF (dist_compatible_tensor) THEN
     367        24256 :          CALL dbt_copy_nocomm(in_tmp_3, out_tmp_1, summation)
     368        24256 :          IF (move_prv) CALL dbt_clear(in_tmp_3)
     369       349343 :       ELSE IF (crop_reshape) THEN
     370          938 :          CALL dbt_reshape(in_tmp_3, out_tmp_1, summation, move_data=move_prv, bounds=bounds)
     371              :       ELSE
     372       348405 :          CALL dbt_reshape(in_tmp_3, out_tmp_1, summation, move_data=move_prv)
     373              :       END IF
     374              : 
     375       728681 :       IF (new_in_1) THEN
     376         4834 :          CALL dbt_destroy(in_tmp_1)
     377         4834 :          DEALLOCATE (in_tmp_1)
     378              :       END IF
     379              : 
     380       728681 :       IF (new_in_2) THEN
     381        96245 :          CALL dbt_destroy(in_tmp_2)
     382        96245 :          DEALLOCATE (in_tmp_2)
     383              :       END IF
     384              : 
     385       728681 :       IF (new_in_3) THEN
     386       208642 :          CALL dbt_destroy(in_tmp_3)
     387       208642 :          DEALLOCATE (in_tmp_3)
     388              :       END IF
     389              : 
     390       728681 :       IF (new_out_1) THEN
     391        96245 :          IF (unit_nr_prv /= 0) THEN
     392            0 :             CALL dbt_write_tensor_dist(out_tmp_1, unit_nr)
     393              :          END IF
     394        96245 :          CALL dbt_split_copyback(out_tmp_1, tensor_out, summation)
     395        96245 :          CALL dbt_destroy(out_tmp_1)
     396        96245 :          DEALLOCATE (out_tmp_1)
     397              :       END IF
     398              : 
     399       728681 :       CALL timestop(handle)
     400              : 
     401      1463134 :    END SUBROUTINE dbt_copy_expert
     402              : 
     403              : ! **************************************************************************************************
     404              : !> \brief Whether dbt_copy_expert (without order) copies by dbt_reshape: compatible blocks, but
     405              : !>        neither the matrix layout nor the distribution allow a copy without communication.
     406              : !> \author Hans Pabst
     407              : ! **************************************************************************************************
     408         4622 :    FUNCTION copy_reshapes(tensor_in, tensor_out)
     409              :       TYPE(dbt_type), INTENT(INOUT)                      :: tensor_in, tensor_out
     410              :       LOGICAL                                            :: copy_reshapes
     411              : 
     412         9244 :       INTEGER, DIMENSION(ndims_matrix_row(tensor_in))    :: map1_in_1
     413         9244 :       INTEGER, DIMENSION(ndims_matrix_column(tensor_in)) :: map1_in_2
     414         9244 :       INTEGER, DIMENSION(ndims_matrix_row(tensor_out))   :: map2_in_1
     415         9244 :       INTEGER, DIMENSION(ndims_matrix_column(tensor_out)) :: map2_in_2
     416              : 
     417         4622 :       copy_reshapes = check_equal(tensor_in%blk_sizes, tensor_out%blk_sizes)
     418         4622 :       IF (copy_reshapes) THEN
     419         4622 :          CALL dbt_get_mapping_info(tensor_in%nd_index, map1_2d=map1_in_1, map2_2d=map1_in_2)
     420         4622 :          CALL dbt_get_mapping_info(tensor_out%nd_index, map1_2d=map2_in_1, map2_2d=map2_in_2)
     421        60054 :          IF (array_eq_i([map1_in_1, map1_in_2], [map2_in_1, map2_in_2])) THEN
     422         4618 :             copy_reshapes = .NOT. check_equal(tensor_in%nd_dist, tensor_out%nd_dist)
     423              :          END IF
     424              :       END IF
     425         4622 :    END FUNCTION copy_reshapes
     426              : 
     427              : ! **************************************************************************************************
     428              : !> \brief copy without communication, requires that both tensors have same process grid and distribution
     429              : !> \param summation Whether to sum matrices b = a + b
     430              : !> \author Patrick Seewald
     431              : ! **************************************************************************************************
     432        24256 :    SUBROUTINE dbt_copy_nocomm(tensor_in, tensor_out, summation)
     433              :       TYPE(dbt_type), INTENT(INOUT) :: tensor_in
     434              :       TYPE(dbt_type), INTENT(INOUT) :: tensor_out
     435              :       LOGICAL, INTENT(IN), OPTIONAL                      :: summation
     436              :       TYPE(dbt_iterator_type) :: iter
     437        24256 :       INTEGER, DIMENSION(ndims_tensor(tensor_in))  :: ind_nd
     438        24256 :       TYPE(block_nd) :: blk_data
     439              :       LOGICAL :: found
     440              : 
     441              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'dbt_copy_nocomm'
     442              :       INTEGER :: handle
     443              : 
     444        24256 :       CALL timeset(routineN, handle)
     445        24256 :       CPASSERT(tensor_out%valid)
     446              : 
     447        24256 :       IF (PRESENT(summation)) THEN
     448        11394 :          IF (.NOT. summation) CALL dbt_clear(tensor_out)
     449              :       ELSE
     450        12862 :          CALL dbt_clear(tensor_out)
     451              :       END IF
     452              : 
     453        24256 :       CALL dbt_reserve_blocks(tensor_in, tensor_out)
     454              : 
     455              : !$OMP PARALLEL DEFAULT(NONE) SHARED(tensor_in,tensor_out,summation) &
     456        24256 : !$OMP PRIVATE(iter,ind_nd,blk_data,found)
     457              :       CALL dbt_iterator_start(iter, tensor_in)
     458              :       DO WHILE (dbt_iterator_blocks_left(iter))
     459              :          CALL dbt_iterator_next_block(iter, ind_nd)
     460              :          CALL dbt_get_block(tensor_in, ind_nd, blk_data, found)
     461              :          CPASSERT(found)
     462              :          CALL dbt_put_block(tensor_out, ind_nd, blk_data, summation=summation)
     463              :          CALL destroy_block(blk_data)
     464              :       END DO
     465              :       CALL dbt_iterator_stop(iter)
     466              : !$OMP END PARALLEL
     467              : 
     468        24256 :       CALL timestop(handle)
     469        48512 :    END SUBROUTINE dbt_copy_nocomm
     470              : 
     471              : ! **************************************************************************************************
     472              : !> \brief copy matrix to tensor.
     473              : !> \param summation tensor_out = tensor_out + matrix_in
     474              : !> \author Patrick Seewald
     475              : ! **************************************************************************************************
     476       126351 :    SUBROUTINE dbt_copy_matrix_to_tensor(matrix_in, tensor_out, summation)
     477              :       TYPE(dbcsr_type), TARGET, INTENT(IN)               :: matrix_in
     478              :       TYPE(dbt_type), INTENT(INOUT)             :: tensor_out
     479              :       LOGICAL, INTENT(IN), OPTIONAL                      :: summation
     480              :       TYPE(dbcsr_type), POINTER                          :: matrix_in_desym
     481              : 
     482              :       INTEGER, DIMENSION(2)                              :: ind_2d
     483       126351 :       REAL(KIND=dp), ALLOCATABLE, DIMENSION(:, :)    :: block_arr
     484       126351 :       REAL(KIND=dp), DIMENSION(:, :), POINTER        :: block
     485              :       TYPE(dbcsr_iterator_type)                          :: iter
     486              : 
     487              :       INTEGER                                            :: handle
     488              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'dbt_copy_matrix_to_tensor'
     489              : 
     490       126351 :       CALL timeset(routineN, handle)
     491       126351 :       CPASSERT(tensor_out%valid)
     492              : 
     493       126351 :       NULLIFY (block)
     494              : 
     495       126351 :       IF (dbcsr_has_symmetry(matrix_in)) THEN
     496         7066 :          ALLOCATE (matrix_in_desym)
     497         7066 :          CALL dbcsr_desymmetrize(matrix_in, matrix_in_desym)
     498              :       ELSE
     499              :          matrix_in_desym => matrix_in
     500              :       END IF
     501              : 
     502       126351 :       IF (PRESENT(summation)) THEN
     503            0 :          IF (.NOT. summation) CALL dbt_clear(tensor_out)
     504              :       ELSE
     505       126351 :          CALL dbt_clear(tensor_out)
     506              :       END IF
     507              : 
     508       126351 :       CALL dbt_reserve_blocks(matrix_in_desym, tensor_out)
     509              : 
     510              : !$OMP PARALLEL DEFAULT(NONE) SHARED(matrix_in_desym,tensor_out,summation) &
     511       126351 : !$OMP PRIVATE(iter,ind_2d,block,block_arr)
     512              :       CALL dbcsr_iterator_start(iter, matrix_in_desym)
     513              :       DO WHILE (dbcsr_iterator_blocks_left(iter))
     514              :          CALL dbcsr_iterator_next_block(iter, ind_2d(1), ind_2d(2), block)
     515              :          CALL allocate_any(block_arr, source=block)
     516              :          CALL dbt_put_block(tensor_out, ind_2d, SHAPE(block_arr), block_arr, summation=summation)
     517              :          DEALLOCATE (block_arr)
     518              :       END DO
     519              :       CALL dbcsr_iterator_stop(iter)
     520              : !$OMP END PARALLEL
     521              : 
     522       126351 :       IF (dbcsr_has_symmetry(matrix_in)) THEN
     523         7066 :          CALL dbcsr_release(matrix_in_desym)
     524         7066 :          DEALLOCATE (matrix_in_desym)
     525              :       END IF
     526              : 
     527       126351 :       CALL timestop(handle)
     528              : 
     529       252702 :    END SUBROUTINE dbt_copy_matrix_to_tensor
     530              : 
     531              : ! **************************************************************************************************
     532              : !> \brief copy tensor to matrix
     533              : !> \param summation matrix_out = matrix_out + tensor_in
     534              : !> \author Patrick Seewald
     535              : ! **************************************************************************************************
     536        86434 :    SUBROUTINE dbt_copy_tensor_to_matrix(tensor_in, matrix_out, summation)
     537              :       TYPE(dbt_type), INTENT(INOUT)      :: tensor_in
     538              :       TYPE(dbcsr_type), INTENT(INOUT)             :: matrix_out
     539              :       LOGICAL, INTENT(IN), OPTIONAL          :: summation
     540              :       TYPE(dbt_iterator_type)            :: iter
     541              :       INTEGER                                :: handle
     542              :       INTEGER, DIMENSION(2)                  :: ind_2d
     543        86434 :       REAL(KIND=dp), DIMENSION(:, :), ALLOCATABLE :: block
     544              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'dbt_copy_tensor_to_matrix'
     545              :       LOGICAL :: found
     546              : 
     547        86434 :       CALL timeset(routineN, handle)
     548              : 
     549        86434 :       IF (PRESENT(summation)) THEN
     550         6966 :          IF (.NOT. summation) CALL dbcsr_clear(matrix_out)
     551              :       ELSE
     552        79468 :          CALL dbcsr_clear(matrix_out)
     553              :       END IF
     554              : 
     555        86434 :       CALL dbt_reserve_blocks(tensor_in, matrix_out)
     556              : 
     557              : !$OMP PARALLEL DEFAULT(NONE) SHARED(tensor_in,matrix_out,summation) &
     558        86434 : !$OMP PRIVATE(iter,ind_2d,block,found)
     559              :       CALL dbt_iterator_start(iter, tensor_in)
     560              :       DO WHILE (dbt_iterator_blocks_left(iter))
     561              :          CALL dbt_iterator_next_block(iter, ind_2d)
     562              :          IF (dbcsr_has_symmetry(matrix_out) .AND. checker_tr(ind_2d(1), ind_2d(2))) CYCLE
     563              : 
     564              :          CALL dbt_get_block(tensor_in, ind_2d, block, found)
     565              :          CPASSERT(found)
     566              : 
     567              :          IF (dbcsr_has_symmetry(matrix_out) .AND. ind_2d(1) > ind_2d(2)) THEN
     568              :             CALL dbcsr_put_block(matrix_out, ind_2d(2), ind_2d(1), TRANSPOSE(block), summation=summation)
     569              :          ELSE
     570              :             CALL dbcsr_put_block(matrix_out, ind_2d(1), ind_2d(2), block, summation=summation)
     571              :          END IF
     572              :          DEALLOCATE (block)
     573              :       END DO
     574              :       CALL dbt_iterator_stop(iter)
     575              : !$OMP END PARALLEL
     576              : 
     577        86434 :       CALL timestop(handle)
     578              : 
     579       172868 :    END SUBROUTINE dbt_copy_tensor_to_matrix
     580              : 
     581              : ! **************************************************************************************************
     582              : !> \brief Contract tensors by multiplying matrix representations.
     583              : !>        tensor_3(map_1, map_2) := alpha * tensor_1(notcontract_1, contract_1)
     584              : !>        * tensor_2(contract_2, notcontract_2)
     585              : !>        + beta * tensor_3(map_1, map_2)
     586              : !>
     587              : !> \note
     588              : !>      note 1: block sizes of the corresponding indices need to be the same in all tensors.
     589              : !>
     590              : !>      note 2: for best performance the tensors should have been created in matrix layouts
     591              : !>      compatible with the contraction, e.g. tensor_1 should have been created with either
     592              : !>      map1_2d == contract_1 and map2_2d == notcontract_1 or map1_2d == notcontract_1 and
     593              : !>      map2_2d == contract_1 (the same with tensor_2 and contract_2 / notcontract_2 and with
     594              : !>      tensor_3 and map_1 / map_2).
     595              : !>      Furthermore the two largest tensors involved in the contraction should map both to either
     596              : !>      tall or short matrices: the largest matrix dimension should be "on the same side"
     597              : !>      and should have identical distribution (which is always the case if the distributions were
     598              : !>      obtained with dbt_default_distvec).
     599              : !>
     600              : !>      note 3: if the same tensor occurs in multiple contractions, a different tensor object should
     601              : !>      be created for each contraction and the data should be copied between the tensors by use of
     602              : !>      dbt_copy. If the same tensor object is used in multiple contractions,
     603              : !>       matrix layouts are not compatible for all contractions (see note 2).
     604              : !>
     605              : !>      note 4: automatic optimizations are enabled by using the feature of batched contraction, see
     606              : !>      dbt_batched_contract_init, dbt_batched_contract_finalize.
     607              : !>      The arguments bounds_1, bounds_2, bounds_3 give the index ranges of the batches.
     608              : !>
     609              : !> \param tensor_1 first tensor (in)
     610              : !> \param tensor_2 second tensor (in)
     611              : !> \param contract_1 indices of tensor_1 to contract
     612              : !> \param contract_2 indices of tensor_2 to contract (1:1 with contract_1)
     613              : !> \param map_1 which indices of tensor_3 map to non-contracted indices of tensor_1 (1:1 with notcontract_1)
     614              : !> \param map_2 which indices of tensor_3 map to non-contracted indices of tensor_2 (1:1 with notcontract_2)
     615              : !> \param notcontract_1 indices of tensor_1 not to contract
     616              : !> \param notcontract_2 indices of tensor_2 not to contract
     617              : !> \param tensor_3 contracted tensor (out)
     618              : !> \param bounds_1 bounds corresponding to contract_1 AKA contract_2:
     619              : !>                 start and end index of an index range over which to contract.
     620              : !>                 For use in batched contraction.
     621              : !> \param bounds_2 bounds corresponding to notcontract_1: start and end index of an index range.
     622              : !>                 For use in batched contraction.
     623              : !> \param bounds_3 bounds corresponding to notcontract_2: start and end index of an index range.
     624              : !>                 For use in batched contraction.
     625              : !> \param optimize_dist Whether distribution should be optimized internally. In the current
     626              : !>                      implementation this guarantees optimal parameters only for dense matrices.
     627              : !> \param pgrid_opt_1 Optionally return optimal process grid for tensor_1.
     628              : !>                    This can be used to choose optimal process grids for subsequent tensor
     629              : !>                    contractions with tensors of similar shape and sparsity. Under some conditions,
     630              : !>                    pgrid_opt_1 can not be returned, in this case the pointer is not associated.
     631              : !> \param pgrid_opt_2 Optionally return optimal process grid for tensor_2.
     632              : !> \param pgrid_opt_3 Optionally return optimal process grid for tensor_3.
     633              : !> \param filter_eps As in DBM mm
     634              : !> \param flop As in DBM mm
     635              : !> \param move_data memory optimization: transfer data such that tensor_1 and tensor_2 are empty on return
     636              : !> \param retain_sparsity enforce the sparsity pattern of the existing tensor_3; default is no
     637              : !> \param unit_nr output unit for logging
     638              : !>                       set it to -1 on ranks that should not write (and any valid unit number on
     639              : !>                       ranks that should write output) if 0 on ALL ranks, no output is written
     640              : !> \param log_verbose verbose logging (for testing only)
     641              : !> \author Patrick Seewald
     642              : ! **************************************************************************************************
     643       585710 :    SUBROUTINE dbt_contract(alpha, tensor_1, tensor_2, beta, tensor_3, &
     644       292855 :                            contract_1, notcontract_1, &
     645       292855 :                            contract_2, notcontract_2, &
     646       292855 :                            map_1, map_2, &
     647       292855 :                            bounds_1, bounds_2, bounds_3, &
     648              :                            optimize_dist, pgrid_opt_1, pgrid_opt_2, pgrid_opt_3, &
     649              :                            filter_eps, flop, move_data, retain_sparsity, unit_nr, log_verbose)
     650              :       REAL(dp), INTENT(IN)            :: alpha
     651              :       TYPE(dbt_type), INTENT(INOUT), TARGET      :: tensor_1
     652              :       TYPE(dbt_type), INTENT(INOUT), TARGET      :: tensor_2
     653              :       REAL(dp), INTENT(IN)            :: beta
     654              :       INTEGER, DIMENSION(:), INTENT(IN)              :: contract_1
     655              :       INTEGER, DIMENSION(:), INTENT(IN)              :: contract_2
     656              :       INTEGER, DIMENSION(:), INTENT(IN)              :: map_1
     657              :       INTEGER, DIMENSION(:), INTENT(IN)              :: map_2
     658              :       INTEGER, DIMENSION(:), INTENT(IN)              :: notcontract_1
     659              :       INTEGER, DIMENSION(:), INTENT(IN)              :: notcontract_2
     660              :       TYPE(dbt_type), INTENT(INOUT), TARGET      :: tensor_3
     661              :       INTEGER, DIMENSION(2, SIZE(contract_1)), &
     662              :          INTENT(IN), OPTIONAL                        :: bounds_1
     663              :       INTEGER, DIMENSION(2, SIZE(notcontract_1)), &
     664              :          INTENT(IN), OPTIONAL                        :: bounds_2
     665              :       INTEGER, DIMENSION(2, SIZE(notcontract_2)), &
     666              :          INTENT(IN), OPTIONAL                        :: bounds_3
     667              :       LOGICAL, INTENT(IN), OPTIONAL                  :: optimize_dist
     668              :       TYPE(dbt_pgrid_type), INTENT(OUT), &
     669              :          POINTER, OPTIONAL                           :: pgrid_opt_1
     670              :       TYPE(dbt_pgrid_type), INTENT(OUT), &
     671              :          POINTER, OPTIONAL                           :: pgrid_opt_2
     672              :       TYPE(dbt_pgrid_type), INTENT(OUT), &
     673              :          POINTER, OPTIONAL                           :: pgrid_opt_3
     674              :       REAL(KIND=dp), INTENT(IN), OPTIONAL        :: filter_eps
     675              :       INTEGER(KIND=int_8), INTENT(OUT), OPTIONAL     :: flop
     676              :       LOGICAL, INTENT(IN), OPTIONAL                  :: move_data
     677              :       LOGICAL, INTENT(IN), OPTIONAL                  :: retain_sparsity
     678              :       INTEGER, OPTIONAL, INTENT(IN)                  :: unit_nr
     679              :       LOGICAL, INTENT(IN), OPTIONAL                  :: log_verbose
     680              : 
     681              :       INTEGER                     :: handle
     682              : 
     683       292855 :       CALL timeset("dbt_total", handle)
     684              :       CALL dbt_contract_expert(alpha, tensor_1, tensor_2, beta, tensor_3, &
     685              :                                contract_1, notcontract_1, &
     686              :                                contract_2, notcontract_2, &
     687              :                                map_1, map_2, &
     688              :                                bounds_1=bounds_1, &
     689              :                                bounds_2=bounds_2, &
     690              :                                bounds_3=bounds_3, &
     691              :                                optimize_dist=optimize_dist, &
     692              :                                pgrid_opt_1=pgrid_opt_1, &
     693              :                                pgrid_opt_2=pgrid_opt_2, &
     694              :                                pgrid_opt_3=pgrid_opt_3, &
     695              :                                filter_eps=filter_eps, &
     696              :                                flop=flop, &
     697              :                                move_data=move_data, &
     698              :                                retain_sparsity=retain_sparsity, &
     699              :                                unit_nr=unit_nr, &
     700       292855 :                                log_verbose=log_verbose)
     701       292855 :       CALL timestop(handle)
     702              : 
     703       292855 :    END SUBROUTINE dbt_contract
     704              : 
     705              : ! **************************************************************************************************
     706              : !> \brief expert routine for tensor contraction. For internal use only.
     707              : !> \param nblks_local number of local blocks on this MPI rank
     708              : !> \author Patrick Seewald
     709              : ! **************************************************************************************************
     710       292855 :    SUBROUTINE dbt_contract_expert(alpha, tensor_1, tensor_2, beta, tensor_3, &
     711       292855 :                                   contract_1, notcontract_1, &
     712       292855 :                                   contract_2, notcontract_2, &
     713       292855 :                                   map_1, map_2, &
     714       292855 :                                   bounds_1, bounds_2, bounds_3, &
     715              :                                   optimize_dist, pgrid_opt_1, pgrid_opt_2, pgrid_opt_3, &
     716              :                                   filter_eps, flop, move_data, retain_sparsity, &
     717              :                                   nblks_local, unit_nr, log_verbose)
     718              :       REAL(dp), INTENT(IN)            :: alpha
     719              :       TYPE(dbt_type), INTENT(INOUT), TARGET      :: tensor_1
     720              :       TYPE(dbt_type), INTENT(INOUT), TARGET      :: tensor_2
     721              :       REAL(dp), INTENT(IN)            :: beta
     722              :       INTEGER, DIMENSION(:), INTENT(IN)              :: contract_1
     723              :       INTEGER, DIMENSION(:), INTENT(IN)              :: contract_2
     724              :       INTEGER, DIMENSION(:), INTENT(IN)              :: map_1
     725              :       INTEGER, DIMENSION(:), INTENT(IN)              :: map_2
     726              :       INTEGER, DIMENSION(:), INTENT(IN)              :: notcontract_1
     727              :       INTEGER, DIMENSION(:), INTENT(IN)              :: notcontract_2
     728              :       TYPE(dbt_type), INTENT(INOUT), TARGET      :: tensor_3
     729              :       INTEGER, DIMENSION(2, SIZE(contract_1)), &
     730              :          INTENT(IN), OPTIONAL                        :: bounds_1
     731              :       INTEGER, DIMENSION(2, SIZE(notcontract_1)), &
     732              :          INTENT(IN), OPTIONAL                        :: bounds_2
     733              :       INTEGER, DIMENSION(2, SIZE(notcontract_2)), &
     734              :          INTENT(IN), OPTIONAL                        :: bounds_3
     735              :       LOGICAL, INTENT(IN), OPTIONAL                  :: optimize_dist
     736              :       TYPE(dbt_pgrid_type), INTENT(OUT), &
     737              :          POINTER, OPTIONAL                           :: pgrid_opt_1
     738              :       TYPE(dbt_pgrid_type), INTENT(OUT), &
     739              :          POINTER, OPTIONAL                           :: pgrid_opt_2
     740              :       TYPE(dbt_pgrid_type), INTENT(OUT), &
     741              :          POINTER, OPTIONAL                           :: pgrid_opt_3
     742              :       REAL(KIND=dp), INTENT(IN), OPTIONAL        :: filter_eps
     743              :       INTEGER(KIND=int_8), INTENT(OUT), OPTIONAL     :: flop
     744              :       LOGICAL, INTENT(IN), OPTIONAL                  :: move_data
     745              :       LOGICAL, INTENT(IN), OPTIONAL                  :: retain_sparsity
     746              :       INTEGER, INTENT(OUT), OPTIONAL                 :: nblks_local
     747              :       INTEGER, OPTIONAL, INTENT(IN)                  :: unit_nr
     748              :       LOGICAL, INTENT(IN), OPTIONAL                  :: log_verbose
     749              : 
     750              :       TYPE(dbt_type), POINTER                    :: tensor_contr_1, tensor_contr_2, tensor_contr_3
     751      5564245 :       TYPE(dbt_type), TARGET                     :: tensor_algn_1, tensor_algn_2, tensor_algn_3
     752              :       TYPE(dbt_type), POINTER                    :: tensor_crop_1, tensor_crop_2
     753              :       TYPE(dbt_type), POINTER                    :: tensor_small, tensor_large
     754              : 
     755              :       LOGICAL                                        :: assert_stmt, tensors_remapped
     756              :       INTEGER                                        :: max_mm_dim, max_tensor, &
     757              :                                                         unit_nr_prv, ref_tensor, handle
     758       292855 :       TYPE(mp_cart_type) :: mp_comm_opt
     759       585710 :       INTEGER, DIMENSION(SIZE(contract_1))           :: contract_1_mod
     760       585710 :       INTEGER, DIMENSION(SIZE(notcontract_1))        :: notcontract_1_mod
     761       585710 :       INTEGER, DIMENSION(SIZE(contract_2))           :: contract_2_mod
     762       585710 :       INTEGER, DIMENSION(SIZE(notcontract_2))        :: notcontract_2_mod
     763       585710 :       INTEGER, DIMENSION(SIZE(map_1))                :: map_1_mod
     764       585710 :       INTEGER, DIMENSION(SIZE(map_2))                :: map_2_mod
     765              :       LOGICAL                                        :: trans_1, trans_2, trans_3
     766              :       LOGICAL                                        :: new_1, new_2, new_3, move_data_1, move_data_2
     767              :       INTEGER                                        :: ndims1, ndims2, ndims3
     768              :       INTEGER, DIMENSION(2)                          :: occ_1, occ_2 ! blocks in bounds, sticking out
     769       292855 :       INTEGER, DIMENSION(:), ALLOCATABLE             :: dims1, dims2, dims3
     770              : 
     771              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'dbt_contract'
     772       292855 :       CHARACTER(LEN=1), DIMENSION(:), ALLOCATABLE    :: indchar1, indchar2, indchar3, indchar1_mod, &
     773       292855 :                                                         indchar2_mod, indchar3_mod
     774              :       CHARACTER(LEN=1), DIMENSION(15), SAVE :: alph = &
     775              :                                                ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
     776       585710 :       INTEGER, DIMENSION(2, ndims_tensor(tensor_1)) :: bounds_t1
     777       585710 :       INTEGER, DIMENSION(2, ndims_tensor(tensor_2)) :: bounds_t2
     778              :       LOGICAL                                        :: do_crop_1, do_crop_2, do_write_3, nodata_3, do_batched, pgrid_changed, &
     779              :                                                         pgrid_changed_any, do_change_pgrid(2)
     780      3807115 :       TYPE(dbt_tas_split_info)                     :: split_opt, split, split_opt_avg
     781              :       INTEGER, DIMENSION(2) :: pdims_2d_opt, pdims_sub, pdims_sub_opt
     782              :       REAL(dp) :: pdim_ratio, pdim_ratio_opt
     783              :       INTEGER :: istat
     784              :       INTEGER(KIND=int_8) :: flop_prv
     785       585710 :       INTEGER, DIMENSION(ndims_tensor(tensor_1)) :: order_1
     786       585710 :       INTEGER, DIMENSION(ndims_tensor(tensor_2)) :: order_2
     787       292855 :       INTEGER, DIMENSION(:, :), ALLOCATABLE :: bounds_a1, bounds_a2 ! unallocated means absent
     788              :       LOGICAL :: cropped_1, cropped_2
     789              : 
     790       292855 :       NULLIFY (tensor_contr_1, tensor_contr_2, tensor_contr_3, tensor_crop_1, tensor_crop_2, &
     791       292855 :                tensor_small)
     792              : 
     793       292855 :       CALL timeset(routineN, handle)
     794              : 
     795       292855 :       CPASSERT(tensor_1%valid)
     796       292855 :       CPASSERT(tensor_2%valid)
     797       292855 :       CPASSERT(tensor_3%valid)
     798              : 
     799       292855 :       assert_stmt = SIZE(contract_1) == SIZE(contract_2)
     800       292855 :       CPASSERT(assert_stmt)
     801              : 
     802       292855 :       assert_stmt = SIZE(map_1) == SIZE(notcontract_1)
     803       292855 :       CPASSERT(assert_stmt)
     804              : 
     805       292855 :       assert_stmt = SIZE(map_2) == SIZE(notcontract_2)
     806       292855 :       CPASSERT(assert_stmt)
     807              : 
     808       292855 :       assert_stmt = SIZE(notcontract_1) + SIZE(contract_1) == ndims_tensor(tensor_1)
     809       292855 :       CPASSERT(assert_stmt)
     810              : 
     811       292855 :       assert_stmt = SIZE(notcontract_2) + SIZE(contract_2) == ndims_tensor(tensor_2)
     812       292855 :       CPASSERT(assert_stmt)
     813              : 
     814       292855 :       assert_stmt = SIZE(map_1) + SIZE(map_2) == ndims_tensor(tensor_3)
     815       292855 :       CPASSERT(assert_stmt)
     816              : 
     817       292855 :       unit_nr_prv = prep_output_unit(unit_nr)
     818              : 
     819       292855 :       IF (PRESENT(flop)) flop = 0
     820       292855 :       IF (PRESENT(nblks_local)) nblks_local = 0
     821              : 
     822       292855 :       IF (PRESENT(move_data)) THEN
     823        83674 :          move_data_1 = move_data
     824        83674 :          move_data_2 = move_data
     825              :       ELSE
     826       209181 :          move_data_1 = .FALSE.
     827       209181 :          move_data_2 = .FALSE.
     828              :       END IF
     829              : 
     830       292855 :       nodata_3 = .TRUE.
     831       292855 :       IF (PRESENT(retain_sparsity)) THEN
     832         4938 :          IF (retain_sparsity) nodata_3 = .FALSE.
     833              :       END IF
     834              : 
     835              :       CALL dbt_map_bounds_to_tensors(tensor_1, tensor_2, &
     836              :                                      contract_1, notcontract_1, &
     837              :                                      contract_2, notcontract_2, &
     838              :                                      bounds_t1, bounds_t2, &
     839              :                                      bounds_1=bounds_1, bounds_2=bounds_2, bounds_3=bounds_3, &
     840       292855 :                                      do_crop_1=do_crop_1, do_crop_2=do_crop_2)
     841              : 
     842              :       ! cropping is deferred: a tensor that is remapped is cropped while copied (single copy)
     843       292855 :       tensor_crop_1 => tensor_1
     844       292855 :       tensor_crop_2 => tensor_2
     845       292855 :       cropped_1 = .FALSE.
     846       292855 :       cropped_2 = .FALSE.
     847              : 
     848       292855 :       istat = contract_stats_index(tensor_1%name, tensor_2%name, tensor_3%name)
     849              :       ASSOCIATE (s => contract_stats(istat))
     850       292855 :          s%ncalls = s%ncalls + 1
     851              :       END ASSOCIATE
     852              : 
     853              :       ! shortcut for empty tensors
     854              :       ! this is needed to avoid unnecessary work in case user contracts different portions of a
     855              :       ! tensor consecutively to save memory
     856              :       ASSOCIATE (mp_comm => tensor_crop_1%pgrid%mp_comm_2d)
     857       292855 :          IF (do_crop_1) THEN
     858       107006 :             occ_1 = num_blocks_in_bounds(tensor_1, bounds_t1)
     859              :          ELSE
     860       557547 :             occ_1 = [dbt_get_num_blocks(tensor_1), 0]
     861              :          END IF
     862       292855 :          CALL mp_comm%max(occ_1)
     863       292855 :          IF (do_crop_2) THEN
     864       101770 :             occ_2 = num_blocks_in_bounds(tensor_2, bounds_t2)
     865              :          ELSE
     866       573255 :             occ_2 = [dbt_get_num_blocks(tensor_2), 0]
     867              :          END IF
     868       585710 :          CALL mp_comm%max(occ_2)
     869              :       END ASSOCIATE
     870              : 
     871       292855 :       IF (occ_1(1) == 0 .OR. occ_2(1) == 0) THEN
     872        38666 :          contract_stats(istat)%nempty = contract_stats(istat)%nempty + 1
     873        38666 :          CALL dbt_scale(tensor_3, beta)
     874              :          ! as if cropped with move_data (tensor data was transferred into the crop)
     875        38666 :          IF (do_crop_1 .AND. move_data_1) CALL dbt_clear(tensor_1)
     876        38666 :          IF (do_crop_2 .AND. move_data_2) CALL dbt_clear(tensor_2)
     877              : 
     878        38666 :          CALL timestop(handle)
     879        38666 :          RETURN
     880              :       END IF
     881              : 
     882              :       ! no block sticks out on any rank: a crop would copy the tensor as is
     883       254189 :       do_crop_1 = do_crop_1 .AND. occ_1(2) > 0
     884       254189 :       do_crop_2 = do_crop_2 .AND. occ_2(2) > 0
     885              :       ASSOCIATE (s => contract_stats(istat))
     886        45797 :          IF (do_crop_1) s%ncrop(1) = s%ncrop(1) + 1
     887       299986 :          IF (do_crop_2) s%ncrop(2) = s%ncrop(2) + 1
     888              :       END ASSOCIATE
     889              : 
     890       254189 :       IF (unit_nr_prv /= 0) THEN
     891        73956 :          IF (unit_nr_prv > 0) THEN
     892           10 :             WRITE (unit_nr_prv, '(A)') repeat("-", 80)
     893           10 :             WRITE (unit_nr_prv, '(A,1X,A,1X,A,1X,A,1X,A,1X,A)') "DBT TENSOR CONTRACTION:", &
     894           20 :                TRIM(tensor_crop_1%name), 'x', TRIM(tensor_crop_2%name), '=', TRIM(tensor_3%name)
     895           10 :             WRITE (unit_nr_prv, '(A)') repeat("-", 80)
     896              :          END IF
     897        73956 :          CALL dbt_write_tensor_info(tensor_crop_1, unit_nr_prv, full_info=log_verbose)
     898        73956 :          CALL dbt_write_tensor_dist(tensor_crop_1, unit_nr_prv)
     899        73956 :          CALL dbt_write_tensor_info(tensor_crop_2, unit_nr_prv, full_info=log_verbose)
     900        73956 :          CALL dbt_write_tensor_dist(tensor_crop_2, unit_nr_prv)
     901              :       END IF
     902              : 
     903              :       ! align tensor index with data, tensor data is not modified
     904       254189 :       ndims1 = ndims_tensor(tensor_crop_1)
     905       254189 :       ndims2 = ndims_tensor(tensor_crop_2)
     906       254189 :       ndims3 = ndims_tensor(tensor_3)
     907      1016756 :       ALLOCATE (indchar1(ndims1), indchar1_mod(ndims1))
     908      1016756 :       ALLOCATE (indchar2(ndims2), indchar2_mod(ndims2))
     909      1016756 :       ALLOCATE (indchar3(ndims3), indchar3_mod(ndims3))
     910              : 
     911              :       ! labeling tensor index with letters
     912              : 
     913      2200862 :       indchar1([notcontract_1, contract_1]) = alph(1:ndims1) ! arb. choice
     914       611208 :       indchar2(notcontract_2) = alph(ndims1 + 1:ndims1 + SIZE(notcontract_2)) ! arb. choice
     915       600552 :       indchar2(contract_2) = indchar1(contract_1)
     916       556717 :       indchar3(map_1) = indchar1(notcontract_1)
     917       611208 :       indchar3(map_2) = indchar2(notcontract_2)
     918              : 
     919       254189 :       IF (unit_nr_prv /= 0) CALL dbt_print_contraction_index(tensor_crop_1, indchar1, &
     920              :                                                              tensor_crop_2, indchar2, &
     921        73956 :                                                              tensor_3, indchar3, unit_nr_prv)
     922       254189 :       IF (unit_nr_prv > 0) THEN
     923           10 :          WRITE (unit_nr_prv, '(T2,A)') "aligning tensor index with data"
     924              :       END IF
     925              : 
     926              :       CALL align_tensor(tensor_crop_1, contract_1, notcontract_1, &
     927       254189 :                         tensor_algn_1, contract_1_mod, notcontract_1_mod, indchar1, indchar1_mod, order_1)
     928              : 
     929              :       CALL align_tensor(tensor_crop_2, contract_2, notcontract_2, &
     930       254189 :                         tensor_algn_2, contract_2_mod, notcontract_2_mod, indchar2, indchar2_mod, order_2)
     931              : 
     932              :       ! bounds in the aligned index order (index i of tensor_X is index order_X(i) of tensor_algn_X)
     933       254189 :       IF (do_crop_1) THEN
     934       137391 :          ALLOCATE (bounds_a1(2, ndims_tensor(tensor_1)))
     935       324671 :          bounds_a1(:, order_1) = bounds_t1(:, :)
     936              :       END IF
     937       254189 :       IF (do_crop_2) THEN
     938       148320 :          ALLOCATE (bounds_a2(2, ndims_tensor(tensor_2)))
     939       458598 :          bounds_a2(:, order_2) = bounds_t2(:, :)
     940              :       END IF
     941              : 
     942              :       CALL align_tensor(tensor_3, map_1, map_2, &
     943       254189 :                         tensor_algn_3, map_1_mod, map_2_mod, indchar3, indchar3_mod)
     944              : 
     945       254189 :       IF (unit_nr_prv /= 0) CALL dbt_print_contraction_index(tensor_algn_1, indchar1_mod, &
     946              :                                                              tensor_algn_2, indchar2_mod, &
     947        73956 :                                                              tensor_algn_3, indchar3_mod, unit_nr_prv)
     948              : 
     949       762567 :       ALLOCATE (dims1(ndims1))
     950       762567 :       ALLOCATE (dims2(ndims2))
     951       762567 :       ALLOCATE (dims3(ndims3))
     952              : 
     953              :       ! ideally we should consider block sizes and occupancy to measure tensor sizes but current solution should work for most
     954              :       ! cases and is more elegant. Note that we can not easily consider occupancy since it is unknown for result tensor
     955       254189 :       CALL blk_dims_tensor(tensor_crop_1, dims1)
     956       254189 :       CALL blk_dims_tensor(tensor_crop_2, dims2)
     957       254189 :       CALL blk_dims_tensor(tensor_3, dims3)
     958              : 
     959              :       max_mm_dim = MAXLOC([PRODUCT(INT(dims1(notcontract_1), int_8)), &
     960              :                            PRODUCT(INT(dims1(contract_1), int_8)), &
     961      2022666 :                            PRODUCT(INT(dims2(notcontract_2), int_8))], DIM=1)
     962      3028576 :       max_tensor = MAXLOC([PRODUCT(INT(dims1, int_8)), PRODUCT(INT(dims2, int_8)), PRODUCT(INT(dims3, int_8))], DIM=1)
     963        59472 :       SELECT CASE (max_mm_dim)
     964              :       CASE (1)
     965        59472 :          IF (unit_nr_prv > 0) THEN
     966            3 :             WRITE (unit_nr_prv, '(T2,A)') "large tensors: 1, 3; small tensor: 2"
     967            3 :             WRITE (unit_nr_prv, '(T2,A)') "sorting contraction indices"
     968              :          END IF
     969        59472 :          CALL index_linked_sort(contract_1_mod, contract_2_mod)
     970        59472 :          CALL index_linked_sort(map_2_mod, notcontract_2_mod)
     971        58870 :          SELECT CASE (max_tensor)
     972              :          CASE (1)
     973        58870 :             CALL index_linked_sort(notcontract_1_mod, map_1_mod)
     974              :          CASE (3)
     975          602 :             CALL index_linked_sort(map_1_mod, notcontract_1_mod)
     976              :          CASE DEFAULT
     977        59472 :             CPABORT("should not happen")
     978              :          END SELECT
     979              : 
     980              :          CALL reshape_mm_compatible(tensor_algn_1, tensor_algn_3, tensor_contr_1, tensor_contr_3, &
     981              :                                     contract_1_mod, notcontract_1_mod, map_2_mod, map_1_mod, &
     982              :                                     trans_1, trans_3, new_1, new_3, ref_tensor, nodata2=nodata_3, optimize_dist=optimize_dist, &
     983              :                                     move_data_1=move_data_1, unit_nr=unit_nr_prv, &
     984        59472 :                                     bounds1=bounds_a1, crop1=cropped_1)
     985              : 
     986              :          CALL reshape_mm_small(tensor_algn_2, contract_2_mod, notcontract_2_mod, tensor_contr_2, trans_2, &
     987              :                                new_2, move_data=move_data_2, unit_nr=unit_nr_prv, &
     988        59472 :                                bounds=bounds_a2, crop=cropped_2)
     989              : 
     990        58870 :          SELECT CASE (ref_tensor)
     991              :          CASE (1)
     992        58870 :             tensor_large => tensor_contr_1
     993              :          CASE (2)
     994        59472 :             tensor_large => tensor_contr_3
     995              :          END SELECT
     996        59472 :          tensor_small => tensor_contr_2
     997              : 
     998              :       CASE (2)
     999        92986 :          IF (unit_nr_prv > 0) THEN
    1000            5 :             WRITE (unit_nr_prv, '(T2,A)') "large tensors: 1, 2; small tensor: 3"
    1001            5 :             WRITE (unit_nr_prv, '(T2,A)') "sorting contraction indices"
    1002              :          END IF
    1003              : 
    1004        92986 :          CALL index_linked_sort(notcontract_1_mod, map_1_mod)
    1005        92986 :          CALL index_linked_sort(notcontract_2_mod, map_2_mod)
    1006        91640 :          SELECT CASE (max_tensor)
    1007              :          CASE (1)
    1008        91640 :             CALL index_linked_sort(contract_1_mod, contract_2_mod)
    1009              :          CASE (2)
    1010         1346 :             CALL index_linked_sort(contract_2_mod, contract_1_mod)
    1011              :          CASE DEFAULT
    1012        92986 :             CPABORT("should not happen")
    1013              :          END SELECT
    1014              : 
    1015              :          CALL reshape_mm_compatible(tensor_algn_1, tensor_algn_2, tensor_contr_1, tensor_contr_2, &
    1016              :                                     notcontract_1_mod, contract_1_mod, notcontract_2_mod, contract_2_mod, &
    1017              :                                     trans_1, trans_2, new_1, new_2, ref_tensor, optimize_dist=optimize_dist, &
    1018              :                                     move_data_1=move_data_1, move_data_2=move_data_2, unit_nr=unit_nr_prv, &
    1019        92986 :                                     bounds1=bounds_a1, bounds2=bounds_a2, crop1=cropped_1, crop2=cropped_2)
    1020        92986 :          trans_1 = .NOT. trans_1
    1021              : 
    1022              :          CALL reshape_mm_small(tensor_algn_3, map_1_mod, map_2_mod, tensor_contr_3, trans_3, &
    1023        92986 :                                new_3, nodata=nodata_3, unit_nr=unit_nr_prv)
    1024              : 
    1025        91640 :          SELECT CASE (ref_tensor)
    1026              :          CASE (1)
    1027        91640 :             tensor_large => tensor_contr_1
    1028              :          CASE (2)
    1029        92986 :             tensor_large => tensor_contr_2
    1030              :          END SELECT
    1031        92986 :          tensor_small => tensor_contr_3
    1032              : 
    1033              :       CASE (3)
    1034       101731 :          IF (unit_nr_prv > 0) THEN
    1035            2 :             WRITE (unit_nr_prv, '(T2,A)') "large tensors: 2, 3; small tensor: 1"
    1036            2 :             WRITE (unit_nr_prv, '(T2,A)') "sorting contraction indices"
    1037              :          END IF
    1038       101731 :          CALL index_linked_sort(map_1_mod, notcontract_1_mod)
    1039       101731 :          CALL index_linked_sort(contract_2_mod, contract_1_mod)
    1040       100131 :          SELECT CASE (max_tensor)
    1041              :          CASE (2)
    1042       100131 :             CALL index_linked_sort(notcontract_2_mod, map_2_mod)
    1043              :          CASE (3)
    1044         1600 :             CALL index_linked_sort(map_2_mod, notcontract_2_mod)
    1045              :          CASE DEFAULT
    1046       101731 :             CPABORT("should not happen")
    1047              :          END SELECT
    1048              : 
    1049              :          CALL reshape_mm_compatible(tensor_algn_2, tensor_algn_3, tensor_contr_2, tensor_contr_3, &
    1050              :                                     contract_2_mod, notcontract_2_mod, map_1_mod, map_2_mod, &
    1051              :                                     trans_2, trans_3, new_2, new_3, ref_tensor, nodata2=nodata_3, optimize_dist=optimize_dist, &
    1052              :                                     move_data_1=move_data_2, unit_nr=unit_nr_prv, &
    1053       101731 :                                     bounds1=bounds_a2, crop1=cropped_2)
    1054              : 
    1055       101731 :          trans_2 = .NOT. trans_2
    1056       101731 :          trans_3 = .NOT. trans_3
    1057              : 
    1058              :          CALL reshape_mm_small(tensor_algn_1, notcontract_1_mod, contract_1_mod, tensor_contr_1, &
    1059              :                                trans_1, new_1, move_data=move_data_1, unit_nr=unit_nr_prv, &
    1060       101731 :                                bounds=bounds_a1, crop=cropped_1)
    1061              : 
    1062       100131 :          SELECT CASE (ref_tensor)
    1063              :          CASE (1)
    1064       100131 :             tensor_large => tensor_contr_2
    1065              :          CASE (2)
    1066       101731 :             tensor_large => tensor_contr_3
    1067              :          END SELECT
    1068       355920 :          tensor_small => tensor_contr_1
    1069              : 
    1070              :       END SELECT
    1071              : 
    1072       254189 :       IF (unit_nr_prv /= 0) CALL dbt_print_contraction_index(tensor_contr_1, indchar1_mod, &
    1073              :                                                              tensor_contr_2, indchar2_mod, &
    1074        73956 :                                                              tensor_contr_3, indchar3_mod, unit_nr_prv)
    1075       254189 :       IF (unit_nr_prv /= 0) THEN
    1076        73956 :          IF (new_1) CALL dbt_write_tensor_info(tensor_contr_1, unit_nr_prv, full_info=log_verbose)
    1077        73956 :          IF (new_1) CALL dbt_write_tensor_dist(tensor_contr_1, unit_nr_prv)
    1078        73956 :          IF (new_2) CALL dbt_write_tensor_info(tensor_contr_2, unit_nr_prv, full_info=log_verbose)
    1079        73956 :          IF (new_2) CALL dbt_write_tensor_dist(tensor_contr_2, unit_nr_prv)
    1080              :       END IF
    1081              : 
    1082              :       ASSOCIATE (s => contract_stats(istat))
    1083        45797 :          IF (do_crop_1) s%nzcrop(1) = s%nzcrop(1) + dbt_get_nze(tensor_contr_1)
    1084       254189 :          IF (do_crop_2) s%nzcrop(2) = s%nzcrop(2) + dbt_get_nze(tensor_contr_2)
    1085       254189 :          IF (new_1) THEN
    1086        23272 :             s%nremap(1) = s%nremap(1) + 1
    1087        23272 :             s%nzremap(1) = s%nzremap(1) + dbt_get_nze(tensor_contr_1)
    1088        23272 :             IF (do_crop_1) s%ncrop_remap(1) = s%ncrop_remap(1) + 1
    1089              :          END IF
    1090       508378 :          IF (new_2) THEN
    1091        11169 :             s%nremap(2) = s%nremap(2) + 1
    1092        11169 :             s%nzremap(2) = s%nzremap(2) + dbt_get_nze(tensor_contr_2)
    1093        11169 :             IF (do_crop_2) s%ncrop_remap(2) = s%ncrop_remap(2) + 1
    1094              :          END IF
    1095              :       END ASSOCIATE
    1096              : 
    1097              :       CALL dbt_tas_multiply(trans_1, trans_2, trans_3, alpha, &
    1098              :                             tensor_contr_1%matrix_rep, tensor_contr_2%matrix_rep, &
    1099              :                             beta, &
    1100              :                             tensor_contr_3%matrix_rep, filter_eps=filter_eps, flop=flop_prv, &
    1101              :                             unit_nr=unit_nr_prv, log_verbose=log_verbose, &
    1102              :                             split_opt=split_opt, &
    1103       254189 :                             move_data_a=move_data_1, move_data_b=move_data_2, retain_sparsity=retain_sparsity)
    1104       254189 :       IF (PRESENT(flop)) flop = flop_prv
    1105              :       ASSOCIATE (s => contract_stats(istat))
    1106       254189 :          s%flop = s%flop + flop_prv
    1107       254189 :          IF (new_3) THEN ! result is copied back into tensor_3
    1108        23324 :             s%nremap(3) = s%nremap(3) + 1
    1109        23324 :             s%nzremap(3) = s%nzremap(3) + dbt_get_nze(tensor_contr_3)
    1110              :          END IF
    1111              :       END ASSOCIATE
    1112              : 
    1113       254189 :       IF (PRESENT(pgrid_opt_1)) THEN
    1114            0 :          IF (.NOT. new_1) THEN
    1115            0 :             ALLOCATE (pgrid_opt_1)
    1116            0 :             pgrid_opt_1 = opt_pgrid(tensor_1, split_opt)
    1117              :          END IF
    1118              :       END IF
    1119              : 
    1120       254189 :       IF (PRESENT(pgrid_opt_2)) THEN
    1121            0 :          IF (.NOT. new_2) THEN
    1122            0 :             ALLOCATE (pgrid_opt_2)
    1123            0 :             pgrid_opt_2 = opt_pgrid(tensor_2, split_opt)
    1124              :          END IF
    1125              :       END IF
    1126              : 
    1127       254189 :       IF (PRESENT(pgrid_opt_3)) THEN
    1128            0 :          IF (.NOT. new_3) THEN
    1129            0 :             ALLOCATE (pgrid_opt_3)
    1130            0 :             pgrid_opt_3 = opt_pgrid(tensor_3, split_opt)
    1131              :          END IF
    1132              :       END IF
    1133              : 
    1134       254189 :       do_batched = tensor_small%matrix_rep%do_batched > 0
    1135              : 
    1136       254189 :       tensors_remapped = .FALSE.
    1137       254189 :       IF (new_1 .OR. new_2 .OR. new_3) tensors_remapped = .TRUE.
    1138              : 
    1139        45697 :       IF (tensors_remapped .AND. do_batched) THEN
    1140              :          CALL cp_warn(__LOCATION__, &
    1141            0 :                       "Internal process grid optimization disabled because tensors are not in contraction-compatible format")
    1142              :       END IF
    1143              : 
    1144              :       ! optimize process grid during batched contraction
    1145       254189 :       do_change_pgrid(:) = .FALSE.
    1146       254189 :       IF ((.NOT. tensors_remapped) .AND. do_batched) THEN
    1147              :          ASSOCIATE (storage => tensor_small%contraction_storage)
    1148            0 :             CPASSERT(storage%static)
    1149       123326 :             split = dbt_tas_info(tensor_large%matrix_rep)
    1150              :             do_change_pgrid(:) = &
    1151       123326 :                update_contraction_storage(storage, split_opt, split)
    1152              : 
    1153       491796 :             IF (ANY(do_change_pgrid)) THEN
    1154          754 :                mp_comm_opt = dbt_tas_mp_comm(tensor_small%pgrid%mp_comm_2d, split_opt%split_rowcol, NINT(storage%nsplit_avg))
    1155              :                CALL dbt_tas_create_split(split_opt_avg, mp_comm_opt, split_opt%split_rowcol, &
    1156          754 :                                          NINT(storage%nsplit_avg), own_comm=.TRUE.)
    1157         2262 :                pdims_2d_opt = split_opt_avg%mp_comm%num_pe_cart
    1158              :             END IF
    1159              : 
    1160              :          END ASSOCIATE
    1161              : 
    1162       123326 :          IF (do_change_pgrid(1) .AND. .NOT. do_change_pgrid(2)) THEN
    1163              :             ! check if new grid has better subgrid, if not there is no need to change process grid
    1164         2262 :             pdims_sub_opt = split_opt_avg%mp_comm_group%num_pe_cart
    1165         2262 :             pdims_sub = split%mp_comm_group%num_pe_cart
    1166              : 
    1167         3016 :             pdim_ratio = MAXVAL(REAL(pdims_sub, dp))/MINVAL(pdims_sub)
    1168         3016 :             pdim_ratio_opt = MAXVAL(REAL(pdims_sub_opt, dp))/MINVAL(pdims_sub_opt)
    1169          754 :             IF (pdim_ratio/pdim_ratio_opt <= default_pdims_accept_ratio**2) THEN
    1170            0 :                do_change_pgrid(1) = .FALSE.
    1171            0 :                CALL dbt_tas_release_info(split_opt_avg)
    1172              :             END IF
    1173              :          END IF
    1174              :       END IF
    1175              : 
    1176       254189 :       IF (unit_nr_prv /= 0) THEN
    1177        73956 :          do_write_3 = .TRUE.
    1178        73956 :          IF (tensor_contr_3%matrix_rep%do_batched > 0) THEN
    1179        31068 :             IF (tensor_contr_3%matrix_rep%mm_storage%batched_out) do_write_3 = .FALSE.
    1180              :          END IF
    1181              :          IF (do_write_3) THEN
    1182        42956 :             CALL dbt_write_tensor_info(tensor_contr_3, unit_nr_prv, full_info=log_verbose)
    1183        42956 :             CALL dbt_write_tensor_dist(tensor_contr_3, unit_nr_prv)
    1184              :          END IF
    1185              :       END IF
    1186              : 
    1187       254189 :       IF (new_3) THEN
    1188              :          ! need redistribute if we created new tensor for tensor 3
    1189        23324 :          CALL dbt_scale(tensor_algn_3, beta)
    1190        23324 :          CALL dbt_copy_expert(tensor_contr_3, tensor_algn_3, summation=.TRUE., move_data=.TRUE.)
    1191        23324 :          IF (PRESENT(filter_eps)) CALL dbt_filter(tensor_algn_3, filter_eps)
    1192              :          ! tensor_3 automatically has correct data because tensor_algn_3 contains a matrix
    1193              :          ! pointer to data of tensor_3
    1194              :       END IF
    1195              : 
    1196              :       ! transfer contraction storage
    1197       254189 :       CALL dbt_copy_contraction_storage(tensor_contr_1, tensor_1)
    1198       254189 :       CALL dbt_copy_contraction_storage(tensor_contr_2, tensor_2)
    1199       254189 :       CALL dbt_copy_contraction_storage(tensor_contr_3, tensor_3)
    1200              : 
    1201       254189 :       IF (unit_nr_prv /= 0) THEN
    1202        73956 :          IF (new_3 .AND. do_write_3) CALL dbt_write_tensor_info(tensor_3, unit_nr_prv, full_info=log_verbose)
    1203        73956 :          IF (new_3 .AND. do_write_3) CALL dbt_write_tensor_dist(tensor_3, unit_nr_prv)
    1204              :       END IF
    1205              : 
    1206       254189 :       CALL dbt_destroy(tensor_algn_1)
    1207       254189 :       CALL dbt_destroy(tensor_algn_2)
    1208       254189 :       CALL dbt_destroy(tensor_algn_3)
    1209              : 
    1210       254189 :       IF (new_1 .OR. cropped_1) THEN
    1211        69067 :          CALL dbt_destroy(tensor_contr_1)
    1212        69067 :          DEALLOCATE (tensor_contr_1)
    1213              :       END IF
    1214       254189 :       IF (new_2 .OR. cropped_2) THEN
    1215        60607 :          CALL dbt_destroy(tensor_contr_2)
    1216        60607 :          DEALLOCATE (tensor_contr_2)
    1217              :       END IF
    1218       254189 :       IF (new_3) THEN
    1219        23324 :          CALL dbt_destroy(tensor_contr_3)
    1220        23324 :          DEALLOCATE (tensor_contr_3)
    1221              :       END IF
    1222              : 
    1223       254189 :       IF (PRESENT(move_data)) THEN
    1224        74506 :          IF (move_data) THEN
    1225        56805 :             CALL dbt_clear(tensor_1)
    1226        56805 :             CALL dbt_clear(tensor_2)
    1227              :          END IF
    1228              :       END IF
    1229              : 
    1230       254189 :       IF (unit_nr_prv > 0) THEN
    1231           10 :          WRITE (unit_nr_prv, '(A)') repeat("-", 80)
    1232           10 :          WRITE (unit_nr_prv, '(A)') "TENSOR CONTRACTION DONE"
    1233           10 :          WRITE (unit_nr_prv, '(A)') repeat("-", 80)
    1234              :       END IF
    1235              : 
    1236       761059 :       IF (ANY(do_change_pgrid)) THEN
    1237          754 :          pgrid_changed_any = .FALSE.
    1238            0 :          SELECT CASE (max_mm_dim)
    1239              :          CASE (1)
    1240            0 :             IF (ALLOCATED(tensor_1%contraction_storage) .AND. ALLOCATED(tensor_3%contraction_storage)) THEN
    1241              :                CALL dbt_change_pgrid_2d(tensor_1, tensor_1%pgrid%mp_comm_2d, pdims=pdims_2d_opt, &
    1242              :                                         nsplit=split_opt_avg%ngroup, dimsplit=split_opt_avg%split_rowcol, &
    1243              :                                         pgrid_changed=pgrid_changed, &
    1244            0 :                                         unit_nr=unit_nr_prv)
    1245            0 :                IF (pgrid_changed) pgrid_changed_any = .TRUE.
    1246              :                CALL dbt_change_pgrid_2d(tensor_3, tensor_3%pgrid%mp_comm_2d, pdims=pdims_2d_opt, &
    1247              :                                         nsplit=split_opt_avg%ngroup, dimsplit=split_opt_avg%split_rowcol, &
    1248              :                                         pgrid_changed=pgrid_changed, &
    1249            0 :                                         unit_nr=unit_nr_prv)
    1250            0 :                IF (pgrid_changed) pgrid_changed_any = .TRUE.
    1251              :             END IF
    1252            0 :             IF (pgrid_changed_any) THEN
    1253            0 :                IF (tensor_2%matrix_rep%do_batched == 3) THEN
    1254              :                   ! set flag that process grid has been optimized to make sure that no grid optimizations are done
    1255              :                   ! in TAS multiply algorithm
    1256            0 :                   CALL dbt_tas_batched_mm_complete(tensor_2%matrix_rep)
    1257              :                END IF
    1258              :             END IF
    1259              :          CASE (2)
    1260          184 :             IF (ALLOCATED(tensor_1%contraction_storage) .AND. ALLOCATED(tensor_2%contraction_storage)) THEN
    1261              :                CALL dbt_change_pgrid_2d(tensor_1, tensor_1%pgrid%mp_comm_2d, pdims=pdims_2d_opt, &
    1262              :                                         nsplit=split_opt_avg%ngroup, dimsplit=split_opt_avg%split_rowcol, &
    1263              :                                         pgrid_changed=pgrid_changed, &
    1264          184 :                                         unit_nr=unit_nr_prv)
    1265          184 :                IF (pgrid_changed) pgrid_changed_any = .TRUE.
    1266              :                CALL dbt_change_pgrid_2d(tensor_2, tensor_2%pgrid%mp_comm_2d, pdims=pdims_2d_opt, &
    1267              :                                         nsplit=split_opt_avg%ngroup, dimsplit=split_opt_avg%split_rowcol, &
    1268              :                                         pgrid_changed=pgrid_changed, &
    1269          184 :                                         unit_nr=unit_nr_prv)
    1270          184 :                IF (pgrid_changed) pgrid_changed_any = .TRUE.
    1271              :             END IF
    1272            8 :             IF (pgrid_changed_any) THEN
    1273          184 :                IF (tensor_3%matrix_rep%do_batched == 3) THEN
    1274          172 :                   CALL dbt_tas_batched_mm_complete(tensor_3%matrix_rep)
    1275              :                END IF
    1276              :             END IF
    1277              :          CASE (3)
    1278          570 :             IF (ALLOCATED(tensor_2%contraction_storage) .AND. ALLOCATED(tensor_3%contraction_storage)) THEN
    1279              :                CALL dbt_change_pgrid_2d(tensor_2, tensor_2%pgrid%mp_comm_2d, pdims=pdims_2d_opt, &
    1280              :                                         nsplit=split_opt_avg%ngroup, dimsplit=split_opt_avg%split_rowcol, &
    1281              :                                         pgrid_changed=pgrid_changed, &
    1282          298 :                                         unit_nr=unit_nr_prv)
    1283          298 :                IF (pgrid_changed) pgrid_changed_any = .TRUE.
    1284              :                CALL dbt_change_pgrid_2d(tensor_3, tensor_3%pgrid%mp_comm_2d, pdims=pdims_2d_opt, &
    1285              :                                         nsplit=split_opt_avg%ngroup, dimsplit=split_opt_avg%split_rowcol, &
    1286              :                                         pgrid_changed=pgrid_changed, &
    1287          298 :                                         unit_nr=unit_nr_prv)
    1288          298 :                IF (pgrid_changed) pgrid_changed_any = .TRUE.
    1289              :             END IF
    1290          754 :             IF (pgrid_changed_any) THEN
    1291          298 :                IF (tensor_1%matrix_rep%do_batched == 3) THEN
    1292          298 :                   CALL dbt_tas_batched_mm_complete(tensor_1%matrix_rep)
    1293              :                END IF
    1294              :             END IF
    1295              :          END SELECT
    1296          754 :          CALL dbt_tas_release_info(split_opt_avg)
    1297              :       END IF
    1298              : 
    1299       254189 :       IF ((.NOT. tensors_remapped) .AND. do_batched) THEN
    1300              :          ! freeze TAS process grids if tensor grids were optimized
    1301       123326 :          CALL dbt_tas_set_batched_state(tensor_1%matrix_rep, opt_grid=.TRUE.)
    1302       123326 :          CALL dbt_tas_set_batched_state(tensor_2%matrix_rep, opt_grid=.TRUE.)
    1303       123326 :          CALL dbt_tas_set_batched_state(tensor_3%matrix_rep, opt_grid=.TRUE.)
    1304              :       END IF
    1305              : 
    1306       254189 :       CALL dbt_tas_release_info(split_opt)
    1307              : 
    1308       254189 :       CALL timestop(handle)
    1309              : 
    1310       839899 :    END SUBROUTINE dbt_contract_expert
    1311              : 
    1312              : ! **************************************************************************************************
    1313              : !> \brief align tensor index with data
    1314              : !> \author Patrick Seewald
    1315              : ! **************************************************************************************************
    1316      6863103 :    SUBROUTINE align_tensor(tensor_in, contract_in, notcontract_in, &
    1317       762567 :                            tensor_out, contract_out, notcontract_out, indp_in, indp_out, order)
    1318              :       TYPE(dbt_type), INTENT(INOUT)               :: tensor_in
    1319              :       INTEGER, DIMENSION(:), INTENT(IN)            :: contract_in, notcontract_in
    1320              :       TYPE(dbt_type), INTENT(OUT)              :: tensor_out
    1321              :       INTEGER, DIMENSION(SIZE(contract_in)), &
    1322              :          INTENT(OUT)                               :: contract_out
    1323              :       INTEGER, DIMENSION(SIZE(notcontract_in)), &
    1324              :          INTENT(OUT)                               :: notcontract_out
    1325              :       CHARACTER(LEN=1), DIMENSION(ndims_tensor(tensor_in)), INTENT(IN) :: indp_in
    1326              :       CHARACTER(LEN=1), DIMENSION(ndims_tensor(tensor_in)), INTENT(OUT) :: indp_out
    1327              :       INTEGER, DIMENSION(ndims_tensor(tensor_in)), INTENT(OUT), OPTIONAL :: order
    1328       762567 :       INTEGER, DIMENSION(ndims_tensor(tensor_in)) :: align
    1329              : 
    1330       762567 :       CALL dbt_align_index(tensor_in, tensor_out, order=align)
    1331      2114840 :       IF (PRESENT(order)) order = align
    1332      1757821 :       contract_out = align(contract_in)
    1333      1779133 :       notcontract_out = align(notcontract_in)
    1334      2774387 :       indp_out(align) = indp_in
    1335              : 
    1336       762567 :    END SUBROUTINE align_tensor
    1337              : 
    1338              : ! **************************************************************************************************
    1339              : !> \brief Prepare tensor for contraction: redistribute to a 2d format which can be contracted by
    1340              : !>        matrix multiplication. This routine reshapes the two largest of the three tensors.
    1341              : !>        Redistribution is avoided if tensors already in a consistent layout.
    1342              : !> \param ind1_free indices of tensor 1 that are "free" (not linked to any index of tensor 2)
    1343              : !> \param ind1_linked indices of tensor 1 that are linked to indices of tensor 2
    1344              : !>                    1:1 correspondence with ind1_linked
    1345              : !> \param trans1 transpose flag of matrix rep. tensor 1
    1346              : !> \param trans2 transpose flag of matrix rep. tensor 2
    1347              : !> \param new1 whether a new tensor 1 was created
    1348              : !> \param new2 whether a new tensor 2 was created
    1349              : !> \param nodata1 don't copy data of tensor 1
    1350              : !> \param nodata2 don't copy data of tensor 2
    1351              : !> \param move_data_1 memory optimization: transfer data s.t. tensor1 may be empty on return
    1352              : !> \param move_data_2 memory optimization: transfer data s.t. tensor2 may be empty on return
    1353              : !> \param optimize_dist experimental: optimize distribution
    1354              : !> \param unit_nr output unit
    1355              : !> \author Patrick Seewald
    1356              : ! **************************************************************************************************
    1357       254189 :    SUBROUTINE reshape_mm_compatible(tensor1, tensor2, tensor1_out, tensor2_out, ind1_free, ind1_linked, &
    1358       254189 :                                     ind2_free, ind2_linked, trans1, trans2, new1, new2, ref_tensor, &
    1359              :                                     nodata1, nodata2, move_data_1, &
    1360              :                                     move_data_2, optimize_dist, unit_nr, bounds1, bounds2, crop1, crop2)
    1361              :       TYPE(dbt_type), TARGET, INTENT(INOUT)   :: tensor1
    1362              :       TYPE(dbt_type), TARGET, INTENT(INOUT)   :: tensor2
    1363              :       TYPE(dbt_type), POINTER, INTENT(OUT)    :: tensor1_out, tensor2_out
    1364              :       INTEGER, DIMENSION(:), INTENT(IN)           :: ind1_free, ind2_free
    1365              :       INTEGER, DIMENSION(:), INTENT(IN)           :: ind1_linked, ind2_linked
    1366              :       LOGICAL, INTENT(OUT)                        :: trans1, trans2
    1367              :       LOGICAL, INTENT(OUT)                        :: new1, new2
    1368              :       INTEGER, INTENT(OUT) :: ref_tensor
    1369              :       LOGICAL, INTENT(IN), OPTIONAL               :: nodata1, nodata2
    1370              :       LOGICAL, INTENT(INOUT), OPTIONAL            :: move_data_1, move_data_2
    1371              :       LOGICAL, INTENT(IN), OPTIONAL               :: optimize_dist
    1372              :       INTEGER, INTENT(IN), OPTIONAL               :: unit_nr
    1373              :       INTEGER, DIMENSION(2, ndims_tensor(tensor1)), INTENT(IN), OPTIONAL :: bounds1
    1374              :       INTEGER, DIMENSION(2, ndims_tensor(tensor2)), INTENT(IN), OPTIONAL :: bounds2
    1375              :       LOGICAL, INTENT(OUT), OPTIONAL              :: crop1, crop2
    1376              :       LOGICAL                                     :: crop1_prv, crop2_prv
    1377              :       INTEGER                                     :: compat1, compat1_old, compat2, compat2_old, &
    1378              :                                                      unit_nr_prv
    1379       254189 :       TYPE(mp_cart_type)                          :: comm_2d
    1380       254189 :       TYPE(array_list)                            :: dist_list
    1381       254189 :       INTEGER, DIMENSION(:), ALLOCATABLE          :: mp_dims
    1382      1779323 :       TYPE(dbt_distribution_type)             :: dist_in
    1383              :       INTEGER(KIND=int_8)                         :: nblkrows, nblkcols
    1384              :       LOGICAL                                     :: optimize_dist_prv
    1385       508378 :       INTEGER, DIMENSION(ndims_tensor(tensor1)) :: dims1
    1386       254189 :       INTEGER, DIMENSION(ndims_tensor(tensor2)) :: dims2
    1387              : 
    1388       254189 :       NULLIFY (tensor1_out, tensor2_out)
    1389              : 
    1390       254189 :       unit_nr_prv = prep_output_unit(unit_nr)
    1391              : 
    1392       254189 :       CALL blk_dims_tensor(tensor1, dims1)
    1393       254189 :       CALL blk_dims_tensor(tensor2, dims2)
    1394              : 
    1395      1754820 :       IF (PRODUCT(int(dims1, int_8)) >= PRODUCT(int(dims2, int_8))) THEN
    1396       250641 :          ref_tensor = 1
    1397              :       ELSE
    1398         3548 :          ref_tensor = 2
    1399              :       END IF
    1400              : 
    1401       254189 :       IF (PRESENT(optimize_dist)) THEN
    1402          484 :          optimize_dist_prv = optimize_dist
    1403              :       ELSE
    1404              :          optimize_dist_prv = .FALSE.
    1405              :       END IF
    1406              : 
    1407       254189 :       compat1 = compat_map(tensor1%nd_index, ind1_linked)
    1408       254189 :       compat2 = compat_map(tensor2%nd_index, ind2_linked)
    1409       254189 :       compat1_old = compat1
    1410       254189 :       compat2_old = compat2
    1411              : 
    1412       254189 :       IF (unit_nr_prv > 0) THEN
    1413           10 :          WRITE (unit_nr_prv, '(T2,A,1X,A,A,1X)', advance='no') "compatibility of", TRIM(tensor1%name), ":"
    1414            6 :          SELECT CASE (compat1)
    1415              :          CASE (0)
    1416            6 :             WRITE (unit_nr_prv, '(A)') "Not compatible"
    1417              :          CASE (1)
    1418            3 :             WRITE (unit_nr_prv, '(A)') "Normal"
    1419              :          CASE (2)
    1420           10 :             WRITE (unit_nr_prv, '(A)') "Transposed"
    1421              :          END SELECT
    1422           10 :          WRITE (unit_nr_prv, '(T2,A,1X,A,A,1X)', advance='no') "compatibility of", TRIM(tensor2%name), ":"
    1423            5 :          SELECT CASE (compat2)
    1424              :          CASE (0)
    1425            5 :             WRITE (unit_nr_prv, '(A)') "Not compatible"
    1426              :          CASE (1)
    1427            4 :             WRITE (unit_nr_prv, '(A)') "Normal"
    1428              :          CASE (2)
    1429           10 :             WRITE (unit_nr_prv, '(A)') "Transposed"
    1430              :          END SELECT
    1431              :       END IF
    1432              : 
    1433       254189 :       new1 = .FALSE.
    1434       254189 :       new2 = .FALSE.
    1435       254189 :       crop1_prv = .FALSE.
    1436       254189 :       crop2_prv = .FALSE.
    1437              : 
    1438       254189 :       IF (compat1 == 0 .OR. optimize_dist_prv) THEN
    1439        34147 :          new1 = .TRUE.
    1440              :       END IF
    1441              : 
    1442       254189 :       IF (compat2 == 0 .OR. optimize_dist_prv) THEN
    1443        23508 :          new2 = .TRUE.
    1444              :       END IF
    1445              : 
    1446       254189 :       IF (ref_tensor == 1) THEN ! tensor 1 is reference and tensor 2 is reshaped compatible with tensor 1
    1447       250641 :          IF (compat1 == 0 .OR. optimize_dist_prv) THEN ! tensor 1 is not contraction compatible --> reshape
    1448        33873 :             IF (unit_nr_prv > 0) WRITE (unit_nr_prv, '(T2,A,1X,A)') "Redistribution of", TRIM(tensor1%name)
    1449       101619 :             nblkrows = PRODUCT(INT(dims1(ind1_linked), KIND=int_8))
    1450        67748 :             nblkcols = PRODUCT(INT(dims1(ind1_free), KIND=int_8))
    1451        33873 :             comm_2d = dbt_tas_mp_comm(tensor1%pgrid%mp_comm_2d, nblkrows, nblkcols)
    1452       237111 :             ALLOCATE (tensor1_out)
    1453              :             CALL dbt_remap(tensor1, ind1_linked, ind1_free, tensor1_out, comm_2d=comm_2d, &
    1454              :                            nodata=nodata1, move_data=move_data_1, &
    1455        33873 :                            bounds=bounds1)
    1456        33873 :             CALL comm_2d%free()
    1457        33873 :             compat1 = 1
    1458              :          ELSE
    1459       216768 :             IF (unit_nr_prv > 0) WRITE (unit_nr_prv, '(T2,A,1X,A)') "No redistribution of", TRIM(tensor1%name)
    1460       216768 :             CALL crop_or_point(tensor1, tensor1_out, crop1_prv, bounds1, move_data_1)
    1461              :          END IF
    1462       250641 :          IF (compat2 == 0 .OR. optimize_dist_prv) THEN ! tensor 2 is not contraction compatible --> reshape
    1463        23172 :             IF (unit_nr_prv > 0) WRITE (unit_nr_prv, '(T2,A,1X,A,1X,A,1X,A)') "Redistribution of", &
    1464            8 :                TRIM(tensor2%name), "compatible with", TRIM(tensor1%name)
    1465        23168 :             dist_in = dbt_distribution(tensor1_out)
    1466        23168 :             dist_list = array_sublist(dist_in%nd_dist, ind1_linked)
    1467        23168 :             IF (compat1 == 1) THEN ! linked index is first 2d dimension
    1468              :                ! get distribution of linked index, tensor 2 must adopt this distribution
    1469              :                ! get grid dimensions of linked index
    1470        35304 :                ALLOCATE (mp_dims(ndims_mapping_row(dist_in%pgrid%nd_index_grid)))
    1471        11768 :                CALL dbt_get_mapping_info(dist_in%pgrid%nd_index_grid, dims1_2d=mp_dims)
    1472        82376 :                ALLOCATE (tensor2_out)
    1473              :                CALL dbt_remap(tensor2, ind2_linked, ind2_free, tensor2_out, comm_2d=dist_in%pgrid%mp_comm_2d, &
    1474              :                               dist1=dist_list, mp_dims_1=mp_dims, nodata=nodata2, move_data=move_data_2, &
    1475        11768 :                               bounds=bounds2)
    1476        11400 :             ELSE IF (compat1 == 2) THEN ! linked index is second 2d dimension
    1477              :                ! get distribution of linked index, tensor 2 must adopt this distribution
    1478              :                ! get grid dimensions of linked index
    1479        34200 :                ALLOCATE (mp_dims(ndims_mapping_column(dist_in%pgrid%nd_index_grid)))
    1480        11400 :                CALL dbt_get_mapping_info(dist_in%pgrid%nd_index_grid, dims2_2d=mp_dims)
    1481        79800 :                ALLOCATE (tensor2_out)
    1482              :                CALL dbt_remap(tensor2, ind2_free, ind2_linked, tensor2_out, comm_2d=dist_in%pgrid%mp_comm_2d, &
    1483              :                               dist2=dist_list, mp_dims_2=mp_dims, nodata=nodata2, move_data=move_data_2, &
    1484        11400 :                               bounds=bounds2)
    1485              :             ELSE
    1486            0 :                CPABORT("should not happen")
    1487              :             END IF
    1488        23168 :             compat2 = compat1
    1489              :          ELSE
    1490       227473 :             IF (unit_nr_prv > 0) WRITE (unit_nr_prv, '(T2,A,1X,A)') "No redistribution of", TRIM(tensor2%name)
    1491       227473 :             CALL crop_or_point(tensor2, tensor2_out, crop2_prv, bounds2, move_data_2)
    1492              :          END IF
    1493              :       ELSE ! tensor 2 is reference and tensor 1 is reshaped compatible with tensor 2
    1494         3548 :          IF (compat2 == 0 .OR. optimize_dist_prv) THEN ! tensor 2 is not contraction compatible --> reshape
    1495          340 :             IF (unit_nr_prv > 0) WRITE (unit_nr_prv, '(T2,A,1X,A)') "Redistribution of", TRIM(tensor2%name)
    1496          766 :             nblkrows = PRODUCT(INT(dims2(ind2_linked), KIND=int_8))
    1497          744 :             nblkcols = PRODUCT(INT(dims2(ind2_free), KIND=int_8))
    1498          340 :             comm_2d = dbt_tas_mp_comm(tensor2%pgrid%mp_comm_2d, nblkrows, nblkcols)
    1499         2380 :             ALLOCATE (tensor2_out)
    1500              :             CALL dbt_remap(tensor2, ind2_linked, ind2_free, tensor2_out, nodata=nodata2, move_data=move_data_2, &
    1501          340 :                            bounds=bounds2)
    1502          340 :             CALL comm_2d%free()
    1503          340 :             compat2 = 1
    1504              :          ELSE
    1505         3208 :             IF (unit_nr_prv > 0) WRITE (unit_nr_prv, '(T2,A,1X,A)') "No redistribution of", TRIM(tensor2%name)
    1506         3208 :             CALL crop_or_point(tensor2, tensor2_out, crop2_prv, bounds2, move_data_2)
    1507              :          END IF
    1508         3548 :          IF (compat1 == 0 .OR. optimize_dist_prv) THEN ! tensor 1 is not contraction compatible --> reshape
    1509          277 :             IF (unit_nr_prv > 0) WRITE (unit_nr_prv, '(T2,A,1X,A,1X,A,1X,A)') "Redistribution of", TRIM(tensor1%name), &
    1510            6 :                "compatible with", TRIM(tensor2%name)
    1511          274 :             dist_in = dbt_distribution(tensor2_out)
    1512          274 :             dist_list = array_sublist(dist_in%nd_dist, ind2_linked)
    1513          274 :             IF (compat2 == 1) THEN
    1514          816 :                ALLOCATE (mp_dims(ndims_mapping_row(dist_in%pgrid%nd_index_grid)))
    1515          272 :                CALL dbt_get_mapping_info(dist_in%pgrid%nd_index_grid, dims1_2d=mp_dims)
    1516         1904 :                ALLOCATE (tensor1_out)
    1517              :                CALL dbt_remap(tensor1, ind1_linked, ind1_free, tensor1_out, comm_2d=dist_in%pgrid%mp_comm_2d, &
    1518              :                               dist1=dist_list, mp_dims_1=mp_dims, nodata=nodata1, move_data=move_data_1, &
    1519          272 :                               bounds=bounds1)
    1520            2 :             ELSE IF (compat2 == 2) THEN
    1521            6 :                ALLOCATE (mp_dims(ndims_mapping_column(dist_in%pgrid%nd_index_grid)))
    1522            2 :                CALL dbt_get_mapping_info(dist_in%pgrid%nd_index_grid, dims2_2d=mp_dims)
    1523           14 :                ALLOCATE (tensor1_out)
    1524              :                CALL dbt_remap(tensor1, ind1_free, ind1_linked, tensor1_out, comm_2d=dist_in%pgrid%mp_comm_2d, &
    1525              :                               dist2=dist_list, mp_dims_2=mp_dims, nodata=nodata1, move_data=move_data_1, &
    1526            2 :                               bounds=bounds1)
    1527              :             ELSE
    1528            0 :                CPABORT("should not happen")
    1529              :             END IF
    1530          274 :             compat1 = compat2
    1531              :          ELSE
    1532         3274 :             IF (unit_nr_prv > 0) WRITE (unit_nr_prv, '(T2,A,1X,A)') "No redistribution of", TRIM(tensor1%name)
    1533         3274 :             CALL crop_or_point(tensor1, tensor1_out, crop1_prv, bounds1, move_data_1)
    1534              :          END IF
    1535              :       END IF
    1536              : 
    1537       175571 :       SELECT CASE (compat1)
    1538              :       CASE (1)
    1539       175571 :          trans1 = .FALSE.
    1540              :       CASE (2)
    1541        78618 :          trans1 = .TRUE.
    1542              :       CASE DEFAULT
    1543       254189 :          CPABORT("should not happen")
    1544              :       END SELECT
    1545              : 
    1546       169610 :       SELECT CASE (compat2)
    1547              :       CASE (1)
    1548       169610 :          trans2 = .FALSE.
    1549              :       CASE (2)
    1550        84579 :          trans2 = .TRUE.
    1551              :       CASE DEFAULT
    1552       254189 :          CPABORT("should not happen")
    1553              :       END SELECT
    1554              : 
    1555       254189 :       IF (unit_nr_prv > 0) THEN
    1556           10 :          IF (compat1 /= compat1_old) THEN
    1557            6 :             WRITE (unit_nr_prv, '(T2,A,1X,A,A,1X)', advance='no') "compatibility of", TRIM(tensor1_out%name), ":"
    1558            0 :             SELECT CASE (compat1)
    1559              :             CASE (0)
    1560            0 :                WRITE (unit_nr_prv, '(A)') "Not compatible"
    1561              :             CASE (1)
    1562            5 :                WRITE (unit_nr_prv, '(A)') "Normal"
    1563              :             CASE (2)
    1564            6 :                WRITE (unit_nr_prv, '(A)') "Transposed"
    1565              :             END SELECT
    1566              :          END IF
    1567           10 :          IF (compat2 /= compat2_old) THEN
    1568            5 :             WRITE (unit_nr_prv, '(T2,A,1X,A,A,1X)', advance='no') "compatibility of", TRIM(tensor2_out%name), ":"
    1569            0 :             SELECT CASE (compat2)
    1570              :             CASE (0)
    1571            0 :                WRITE (unit_nr_prv, '(A)') "Not compatible"
    1572              :             CASE (1)
    1573            4 :                WRITE (unit_nr_prv, '(A)') "Normal"
    1574              :             CASE (2)
    1575            5 :                WRITE (unit_nr_prv, '(A)') "Transposed"
    1576              :             END SELECT
    1577              :          END IF
    1578              :       END IF
    1579              : 
    1580       254189 :       IF (new1 .AND. PRESENT(move_data_1)) move_data_1 = .TRUE.
    1581       254189 :       IF (new2 .AND. PRESENT(move_data_2)) move_data_2 = .TRUE.
    1582              : 
    1583       254189 :       IF (PRESENT(crop1)) crop1 = crop1_prv
    1584       254189 :       IF (PRESENT(crop2)) crop2 = crop2_prv
    1585              : 
    1586       254189 :    END SUBROUTINE reshape_mm_compatible
    1587              : 
    1588              : ! **************************************************************************************************
    1589              : !> \brief Prepare tensor for contraction: redistribute to a 2d format which can be contracted by
    1590              : !>        matrix multiplication. This routine reshapes the smallest of the three tensors.
    1591              : !> \param ind1 index that should be mapped to first matrix dimension
    1592              : !> \param ind2 index that should be mapped to second matrix dimension
    1593              : !> \param trans transpose flag of matrix rep.
    1594              : !> \param new whether a new tensor was created for tensor_out
    1595              : !> \param nodata don't copy tensor data
    1596              : !> \param move_data memory optimization: transfer data s.t. tensor_in may be empty on return
    1597              : !> \param unit_nr output unit
    1598              : !> \author Patrick Seewald
    1599              : ! **************************************************************************************************
    1600       254189 :    SUBROUTINE reshape_mm_small(tensor_in, ind1, ind2, tensor_out, trans, new, nodata, move_data, unit_nr, &
    1601              :                                bounds, crop)
    1602              :       TYPE(dbt_type), TARGET, INTENT(INOUT)   :: tensor_in
    1603              :       INTEGER, DIMENSION(:), INTENT(IN)           :: ind1, ind2
    1604              :       TYPE(dbt_type), POINTER, INTENT(OUT)    :: tensor_out
    1605              :       LOGICAL, INTENT(OUT)                        :: trans
    1606              :       LOGICAL, INTENT(OUT)                        :: new
    1607              :       LOGICAL, INTENT(IN), OPTIONAL               :: nodata
    1608              :       LOGICAL, INTENT(INOUT), OPTIONAL            :: move_data
    1609              :       INTEGER, INTENT(IN), OPTIONAL               :: unit_nr
    1610              :       INTEGER, DIMENSION(2, ndims_tensor(tensor_in)), INTENT(IN), OPTIONAL :: bounds
    1611              :       LOGICAL, INTENT(OUT), OPTIONAL              :: crop
    1612              :       LOGICAL                                     :: crop_prv
    1613              :       INTEGER                                     :: compat1, compat2, compat1_old, compat2_old, unit_nr_prv
    1614              :       LOGICAL                                     :: nodata_prv
    1615              : 
    1616       254189 :       NULLIFY (tensor_out)
    1617              :       IF (PRESENT(nodata)) THEN
    1618       254189 :          nodata_prv = nodata
    1619              :       ELSE
    1620       254189 :          nodata_prv = .FALSE.
    1621              :       END IF
    1622              : 
    1623       254189 :       unit_nr_prv = prep_output_unit(unit_nr)
    1624              : 
    1625       254189 :       new = .FALSE.
    1626       254189 :       crop_prv = .FALSE.
    1627       254189 :       compat1 = compat_map(tensor_in%nd_index, ind1)
    1628       254189 :       compat2 = compat_map(tensor_in%nd_index, ind2)
    1629       254189 :       compat1_old = compat1; compat2_old = compat2
    1630       254189 :       IF (unit_nr_prv > 0) THEN
    1631           10 :          WRITE (unit_nr_prv, '(T2,A,1X,A,A,1X)', advance='no') "compatibility of", TRIM(tensor_in%name), ":"
    1632           10 :          IF (compat1 == 1 .AND. compat2 == 2) THEN
    1633            4 :             WRITE (unit_nr_prv, '(A)') "Normal"
    1634            6 :          ELSE IF (compat1 == 2 .AND. compat2 == 1) THEN
    1635            2 :             WRITE (unit_nr_prv, '(A)') "Transposed"
    1636              :          ELSE
    1637            4 :             WRITE (unit_nr_prv, '(A)') "Not compatible"
    1638              :          END IF
    1639              :       END IF
    1640       254189 :       IF (compat1 == 0 .or. compat2 == 0) THEN ! index mapping not compatible with contract index
    1641              : 
    1642          110 :          IF (unit_nr_prv > 0) WRITE (unit_nr_prv, '(T2,A,1X,A)') "Redistribution of", TRIM(tensor_in%name)
    1643              : 
    1644          770 :          ALLOCATE (tensor_out)
    1645          110 :          CALL dbt_remap(tensor_in, ind1, ind2, tensor_out, nodata=nodata, move_data=move_data, bounds=bounds)
    1646          110 :          CALL dbt_copy_contraction_storage(tensor_in, tensor_out)
    1647          110 :          compat1 = 1
    1648          110 :          compat2 = 2
    1649          110 :          new = .TRUE.
    1650              :       ELSE
    1651       254079 :          IF (unit_nr_prv > 0) WRITE (unit_nr_prv, '(T2,A,1X,A)') "No redistribution of", TRIM(tensor_in%name)
    1652       254079 :          CALL crop_or_point(tensor_in, tensor_out, crop_prv, bounds, move_data)
    1653              :       END IF
    1654              : 
    1655       254189 :       IF (compat1 == 1 .AND. compat2 == 2) THEN
    1656       180248 :          trans = .FALSE.
    1657        73941 :       ELSE IF (compat1 == 2 .AND. compat2 == 1) THEN
    1658        73941 :          trans = .TRUE.
    1659              :       ELSE
    1660            0 :          CPABORT("this should not happen")
    1661              :       END IF
    1662              : 
    1663       254189 :       IF (unit_nr_prv > 0) THEN
    1664           10 :          IF (compat1_old /= compat1 .OR. compat2_old /= compat2) THEN
    1665            4 :             WRITE (unit_nr_prv, '(T2,A,1X,A,A,1X)', advance='no') "compatibility of", TRIM(tensor_out%name), ":"
    1666            4 :             IF (compat1 == 1 .AND. compat2 == 2) THEN
    1667            4 :                WRITE (unit_nr_prv, '(A)') "Normal"
    1668            0 :             ELSE IF (compat1 == 2 .AND. compat2 == 1) THEN
    1669            0 :                WRITE (unit_nr_prv, '(A)') "Transposed"
    1670              :             ELSE
    1671            0 :                WRITE (unit_nr_prv, '(A)') "Not compatible"
    1672              :             END IF
    1673              :          END IF
    1674              :       END IF
    1675              : 
    1676       254189 :       IF (PRESENT(crop)) crop = crop_prv
    1677              : 
    1678       254189 :    END SUBROUTINE reshape_mm_small
    1679              : 
    1680              : ! **************************************************************************************************
    1681              : !> \brief Crop tensor_in into a new tensor_out if bounds are present, otherwise point to tensor_in.
    1682              : !> \param cropped whether tensor_out is a new tensor
    1683              : !> \param move_data memory optimization: transfer data s.t. tensor_in may be empty on return
    1684              : !> \author Hans Pabst
    1685              : ! **************************************************************************************************
    1686       704802 :    SUBROUTINE crop_or_point(tensor_in, tensor_out, cropped, bounds, move_data)
    1687              :       TYPE(dbt_type), TARGET, INTENT(INOUT)   :: tensor_in
    1688              :       TYPE(dbt_type), POINTER, INTENT(OUT)    :: tensor_out
    1689              :       LOGICAL, INTENT(OUT)                        :: cropped
    1690              :       INTEGER, DIMENSION(2, ndims_tensor(tensor_in)), INTENT(IN), OPTIONAL :: bounds
    1691              :       LOGICAL, INTENT(INOUT), OPTIONAL            :: move_data
    1692              : 
    1693       704802 :       cropped = PRESENT(bounds)
    1694       704802 :       IF (cropped) THEN
    1695       952330 :          ALLOCATE (tensor_out)
    1696        95233 :          CALL dbt_crop(tensor_in, tensor_out, bounds, move_data=move_data)
    1697        95233 :          IF (PRESENT(move_data)) move_data = .TRUE. ! tensor_out is temporary
    1698              :       ELSE
    1699       609569 :          tensor_out => tensor_in
    1700              :       END IF
    1701       704802 :    END SUBROUTINE crop_or_point
    1702              : 
    1703              : ! **************************************************************************************************
    1704              : !> \brief Number of local blocks overlapping the bounds (blocks dbt_crop would keep), and number
    1705              : !>        of local blocks not entirely within the bounds (none: dbt_crop would copy as is).
    1706              : !> \author Hans Pabst
    1707              : ! **************************************************************************************************
    1708       417552 :    FUNCTION num_blocks_in_bounds(tensor, bounds) RESULT(nblocks)
    1709              :       TYPE(dbt_type), INTENT(INOUT)                      :: tensor
    1710              :       INTEGER, DIMENSION(2, ndims_tensor(tensor)), INTENT(IN) :: bounds
    1711              :       INTEGER, DIMENSION(2)                              :: nblocks
    1712              : 
    1713              :       TYPE(dbt_iterator_type)                            :: iter
    1714       208776 :       INTEGER, DIMENSION(ndims_tensor(tensor))           :: blk_index, blk_offset, blk_size
    1715              :       INTEGER                                            :: nin, nout
    1716              : 
    1717       208776 :       nin = 0
    1718       208776 :       nout = 0
    1719              : !$OMP PARALLEL DEFAULT(NONE) SHARED(tensor,bounds) PRIVATE(iter,blk_index,blk_size,blk_offset) &
    1720       208776 : !$OMP REDUCTION(+:nin,nout)
    1721              :       CALL dbt_iterator_start(iter, tensor)
    1722              :       DO WHILE (dbt_iterator_blocks_left(iter))
    1723              :          CALL dbt_iterator_next_block(iter, blk_index, blk_size=blk_size, blk_offset=blk_offset)
    1724              :          IF (ALL(blk_offset <= bounds(2, :) .AND. bounds(1, :) <= blk_offset + blk_size - 1)) THEN
    1725              :             nin = nin + 1
    1726              :          END IF
    1727              :          IF (ANY(blk_offset < bounds(1, :) .OR. bounds(2, :) < blk_offset + blk_size - 1)) THEN
    1728              :             nout = nout + 1
    1729              :          END IF
    1730              :       END DO
    1731              :       CALL dbt_iterator_stop(iter)
    1732              : !$OMP END PARALLEL
    1733       626328 :       nblocks = [nin, nout]
    1734       208776 :    END FUNCTION num_blocks_in_bounds
    1735              : 
    1736              : ! **************************************************************************************************
    1737              : !> \brief update contraction storage that keeps track of process grids during a batched contraction
    1738              : !>        and decide if tensor process grid needs to be optimized
    1739              : !> \param split_opt optimized TAS process grid
    1740              : !> \param split current TAS process grid
    1741              : !> \author Patrick Seewald
    1742              : ! **************************************************************************************************
    1743       123326 :    FUNCTION update_contraction_storage(storage, split_opt, split) RESULT(do_change_pgrid)
    1744              :       TYPE(dbt_contraction_storage), INTENT(INOUT) :: storage
    1745              :       TYPE(dbt_tas_split_info), INTENT(IN)           :: split_opt
    1746              :       TYPE(dbt_tas_split_info), INTENT(IN)           :: split
    1747              :       INTEGER, DIMENSION(2) :: pdims, pdims_sub
    1748              :       LOGICAL, DIMENSION(2) :: do_change_pgrid
    1749              :       REAL(kind=dp) :: change_criterion, pdims_ratio
    1750              :       INTEGER :: nsplit_opt, nsplit
    1751              : 
    1752       123326 :       CPASSERT(ALLOCATED(split_opt%ngroup_opt))
    1753       123326 :       nsplit_opt = split_opt%ngroup_opt
    1754       123326 :       nsplit = split%ngroup
    1755              : 
    1756       369978 :       pdims = split%mp_comm%num_pe_cart
    1757              : 
    1758       123326 :       storage%ibatch = storage%ibatch + 1
    1759              : 
    1760              :       storage%nsplit_avg = (storage%nsplit_avg*REAL(storage%ibatch - 1, dp) + REAL(nsplit_opt, dp)) &
    1761       123326 :                            /REAL(storage%ibatch, dp)
    1762              : 
    1763       123326 :       SELECT CASE (split_opt%split_rowcol)
    1764              :       CASE (rowsplit)
    1765       123326 :          pdims_ratio = REAL(pdims(1), dp)/pdims(2)
    1766              :       CASE (colsplit)
    1767       123326 :          pdims_ratio = REAL(pdims(2), dp)/pdims(1)
    1768              :       END SELECT
    1769              : 
    1770       369978 :       do_change_pgrid(:) = .FALSE.
    1771              : 
    1772              :       ! check for process grid dimensions
    1773       369978 :       pdims_sub = split%mp_comm_group%num_pe_cart
    1774       616630 :       change_criterion = MAXVAL(REAL(pdims_sub, dp))/MINVAL(pdims_sub)
    1775       123326 :       IF (change_criterion > default_pdims_accept_ratio**2) do_change_pgrid(1) = .TRUE.
    1776              : 
    1777              :       ! check for split factor
    1778       123326 :       change_criterion = MAX(REAL(nsplit, dp)/storage%nsplit_avg, REAL(storage%nsplit_avg, dp)/nsplit)
    1779       123326 :       IF (change_criterion > default_nsplit_accept_ratio) do_change_pgrid(2) = .TRUE.
    1780              : 
    1781       123326 :    END FUNCTION update_contraction_storage
    1782              : 
    1783              : ! **************************************************************************************************
    1784              : !> \brief Check if 2d index is compatible with tensor index
    1785              : !> \author Patrick Seewald
    1786              : ! **************************************************************************************************
    1787      1016756 :    FUNCTION compat_map(nd_index, compat_ind)
    1788              :       TYPE(nd_to_2d_mapping), INTENT(IN) :: nd_index
    1789              :       INTEGER, DIMENSION(:), INTENT(IN)  :: compat_ind
    1790      2033512 :       INTEGER, DIMENSION(ndims_mapping_row(nd_index)) :: map1
    1791      2033512 :       INTEGER, DIMENSION(ndims_mapping_column(nd_index)) :: map2
    1792              :       INTEGER                            :: compat_map
    1793              : 
    1794      1016756 :       CALL dbt_get_mapping_info(nd_index, map1_2d=map1, map2_2d=map2)
    1795              : 
    1796      1016756 :       compat_map = 0
    1797      1016756 :       IF (array_eq_i(map1, compat_ind)) THEN
    1798              :          compat_map = 1
    1799       463555 :       ELSE IF (array_eq_i(map2, compat_ind)) THEN
    1800       406658 :          compat_map = 2
    1801              :       END IF
    1802              : 
    1803      1016756 :    END FUNCTION compat_map
    1804              : 
    1805              : ! **************************************************************************************************
    1806              : !> \brief
    1807              : !> \author Patrick Seewald
    1808              : ! **************************************************************************************************
    1809       762567 :    SUBROUTINE index_linked_sort(ind_ref, ind_dep)
    1810              :       INTEGER, DIMENSION(:), INTENT(INOUT) :: ind_ref, ind_dep
    1811      1525134 :       INTEGER, DIMENSION(SIZE(ind_ref))    :: sort_indices
    1812              : 
    1813       762567 :       CALL sort(ind_ref, SIZE(ind_ref), sort_indices)
    1814      3536954 :       ind_dep(:) = ind_dep(sort_indices)
    1815              : 
    1816       762567 :    END SUBROUTINE index_linked_sort
    1817              : 
    1818              : ! **************************************************************************************************
    1819              : !> \brief
    1820              : !> \author Patrick Seewald
    1821              : ! **************************************************************************************************
    1822            0 :    FUNCTION opt_pgrid(tensor, tas_split_info)
    1823              :       TYPE(dbt_type), INTENT(IN) :: tensor
    1824              :       TYPE(dbt_tas_split_info), INTENT(IN) :: tas_split_info
    1825            0 :       INTEGER, DIMENSION(ndims_matrix_row(tensor)) :: map1
    1826            0 :       INTEGER, DIMENSION(ndims_matrix_column(tensor)) :: map2
    1827              :       TYPE(dbt_pgrid_type) :: opt_pgrid
    1828            0 :       INTEGER, DIMENSION(ndims_tensor(tensor)) :: dims
    1829              : 
    1830            0 :       CALL dbt_get_mapping_info(tensor%pgrid%nd_index_grid, map1_2d=map1, map2_2d=map2)
    1831            0 :       CALL blk_dims_tensor(tensor, dims)
    1832            0 :       opt_pgrid = dbt_nd_mp_comm(tas_split_info%mp_comm, map1, map2, tdims=dims)
    1833              : 
    1834            0 :       ALLOCATE (opt_pgrid%tas_split_info, SOURCE=tas_split_info)
    1835            0 :       CALL dbt_tas_info_hold(opt_pgrid%tas_split_info)
    1836            0 :    END FUNCTION opt_pgrid
    1837              : 
    1838              : ! **************************************************************************************************
    1839              : !> \brief Copy tensor to tensor with modified index mapping
    1840              : !> \param map1_2d new index mapping
    1841              : !> \param map2_2d new index mapping
    1842              : !> \author Patrick Seewald
    1843              : ! **************************************************************************************************
    1844       519885 :    SUBROUTINE dbt_remap(tensor_in, map1_2d, map2_2d, tensor_out, comm_2d, dist1, dist2, &
    1845        57765 :                         mp_dims_1, mp_dims_2, name, nodata, move_data, bounds)
    1846              :       TYPE(dbt_type), INTENT(INOUT)      :: tensor_in
    1847              :       INTEGER, DIMENSION(2, ndims_tensor(tensor_in)), INTENT(IN), OPTIONAL :: bounds
    1848              :       INTEGER, DIMENSION(:), INTENT(IN)      :: map1_2d, map2_2d
    1849              :       TYPE(dbt_type), INTENT(OUT)        :: tensor_out
    1850              :       CHARACTER(len=*), INTENT(IN), OPTIONAL :: name
    1851              :       LOGICAL, INTENT(IN), OPTIONAL          :: nodata, move_data
    1852              :       CLASS(mp_comm_type), INTENT(IN), OPTIONAL          :: comm_2d
    1853              :       TYPE(array_list), INTENT(IN), OPTIONAL :: dist1, dist2
    1854              :       INTEGER, DIMENSION(SIZE(map1_2d)), OPTIONAL :: mp_dims_1
    1855              :       INTEGER, DIMENSION(SIZE(map2_2d)), OPTIONAL :: mp_dims_2
    1856              :       CHARACTER(len=default_string_length)   :: name_tmp
    1857        57765 :       INTEGER, DIMENSION(:), ALLOCATABLE     :: ${varlist("blk_sizes")}$, &
    1858        57765 :                                                 ${varlist("nd_dist")}$
    1859       404355 :       TYPE(dbt_distribution_type)        :: dist
    1860        57765 :       TYPE(mp_cart_type) :: comm_2d_prv
    1861              :       INTEGER                                :: handle, i
    1862        57765 :       INTEGER, DIMENSION(ndims_tensor(tensor_in)) :: pdims, myploc
    1863              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'dbt_remap'
    1864              :       LOGICAL                               :: nodata_prv
    1865       173295 :       TYPE(dbt_pgrid_type)              :: comm_nd
    1866              : 
    1867        57765 :       CALL timeset(routineN, handle)
    1868              : 
    1869        57765 :       IF (PRESENT(name)) THEN
    1870            0 :          name_tmp = name
    1871              :       ELSE
    1872        57765 :          name_tmp = tensor_in%name
    1873              :       END IF
    1874        57765 :       IF (PRESENT(dist1)) THEN
    1875        12040 :          CPASSERT(PRESENT(mp_dims_1))
    1876              :       END IF
    1877              : 
    1878        57765 :       IF (PRESENT(dist2)) THEN
    1879        11402 :          CPASSERT(PRESENT(mp_dims_2))
    1880              :       END IF
    1881              : 
    1882        57765 :       IF (PRESENT(comm_2d)) THEN
    1883        57315 :          comm_2d_prv = comm_2d
    1884              :       ELSE
    1885          450 :          comm_2d_prv = tensor_in%pgrid%mp_comm_2d
    1886              :       END IF
    1887              : 
    1888        57765 :       comm_nd = dbt_nd_mp_comm(comm_2d_prv, map1_2d, map2_2d, dims1_nd=mp_dims_1, dims2_nd=mp_dims_2)
    1889        57765 :       CALL mp_environ_pgrid(comm_nd, pdims, myploc)
    1890              : 
    1891              :       #:for ndim in ndims
    1892       115526 :          IF (ndims_tensor(tensor_in) == ${ndim}$) THEN
    1893        57765 :             CALL get_arrays(tensor_in%blk_sizes, ${varlist("blk_sizes", nmax=ndim)}$)
    1894              :          END IF
    1895              :       #:endfor
    1896              : 
    1897              :       #:for ndim in ndims
    1898       115526 :          IF (ndims_tensor(tensor_in) == ${ndim}$) THEN
    1899              :             #:for idim in range(1, ndim+1)
    1900       173107 :                IF (PRESENT(dist1)) THEN
    1901        72042 :                   IF (ANY(map1_2d == ${idim}$)) THEN
    1902        71448 :                      i = MINLOC(map1_2d, dim=1, mask=map1_2d == ${idim}$) ! i is location of idim in map1_2d
    1903        23882 :                      CALL get_ith_array(dist1, i, nd_dist_${idim}$)
    1904              :                   END IF
    1905              :                END IF
    1906              : 
    1907       173107 :                IF (PRESENT(dist2)) THEN
    1908        68384 :                   IF (ANY(map2_2d == ${idim}$)) THEN
    1909        68300 :                      i = MINLOC(map2_2d, dim=1, mask=map2_2d == ${idim}$) ! i is location of idim in map2_2d
    1910        22776 :                      CALL get_ith_array(dist2, i, nd_dist_${idim}$)
    1911              :                   END IF
    1912              :                END IF
    1913              : 
    1914       173107 :                IF (.NOT. ALLOCATED(nd_dist_${idim}$)) THEN
    1915       379347 :                   ALLOCATE (nd_dist_${idim}$ (SIZE(blk_sizes_${idim}$)))
    1916       126449 :                   CALL dbt_default_distvec(SIZE(blk_sizes_${idim}$), pdims(${idim}$), blk_sizes_${idim}$, nd_dist_${idim}$)
    1917              :                END IF
    1918              :             #:endfor
    1919              :             CALL dbt_distribution_new_expert(dist, comm_nd, map1_2d, map2_2d, &
    1920        57765 :                                              ${varlist("nd_dist", nmax=ndim)}$, own_comm=.TRUE.)
    1921              :          END IF
    1922              :       #:endfor
    1923              : 
    1924              :       #:for ndim in ndims
    1925       115526 :          IF (ndims_tensor(tensor_in) == ${ndim}$) THEN
    1926              :             CALL dbt_create(tensor_out, name_tmp, dist, map1_2d, map2_2d, &
    1927        57765 :                             ${varlist("blk_sizes", nmax=ndim)}$)
    1928              :          END IF
    1929              :       #:endfor
    1930              : 
    1931        57765 :       IF (PRESENT(nodata)) THEN
    1932        23324 :          nodata_prv = nodata
    1933              :       ELSE
    1934              :          nodata_prv = .FALSE.
    1935              :       END IF
    1936              : 
    1937        57765 :       IF (.NOT. nodata_prv) CALL dbt_copy_expert(tensor_in, tensor_out, move_data=move_data, bounds=bounds)
    1938        57765 :       CALL dbt_distribution_destroy(dist)
    1939              : 
    1940        57765 :       CALL timestop(handle)
    1941       173295 :    END SUBROUTINE dbt_remap
    1942              : 
    1943              : ! **************************************************************************************************
    1944              : !> \brief Align index with data
    1945              : !> \param order permutation resulting from alignment
    1946              : !> \author Patrick Seewald
    1947              : ! **************************************************************************************************
    1948      6100536 :    SUBROUTINE dbt_align_index(tensor_in, tensor_out, order)
    1949              :       TYPE(dbt_type), INTENT(INOUT)               :: tensor_in
    1950              :       TYPE(dbt_type), INTENT(OUT)                 :: tensor_out
    1951      1525134 :       INTEGER, DIMENSION(ndims_matrix_row(tensor_in)) :: map1_2d
    1952      1525134 :       INTEGER, DIMENSION(ndims_matrix_column(tensor_in)) :: map2_2d
    1953              :       INTEGER, DIMENSION(ndims_tensor(tensor_in)), &
    1954              :          INTENT(OUT), OPTIONAL                        :: order
    1955       762567 :       INTEGER, DIMENSION(ndims_tensor(tensor_in))     :: order_prv
    1956              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'dbt_align_index'
    1957              :       INTEGER                                         :: handle
    1958              : 
    1959       762567 :       CALL timeset(routineN, handle)
    1960              : 
    1961       762567 :       CALL dbt_get_mapping_info(tensor_in%nd_index_blk, map1_2d=map1_2d, map2_2d=map2_2d)
    1962      4786207 :       order_prv = dbt_inverse_order([map1_2d, map2_2d])
    1963       762567 :       CALL dbt_permute_index(tensor_in, tensor_out, order=order_prv)
    1964              : 
    1965      2774387 :       IF (PRESENT(order)) order = order_prv
    1966              : 
    1967       762567 :       CALL timestop(handle)
    1968       762567 :    END SUBROUTINE dbt_align_index
    1969              : 
    1970              : ! **************************************************************************************************
    1971              : !> \brief Create new tensor by reordering index, data is copied exactly (shallow copy)
    1972              : !> \author Patrick Seewald
    1973              : ! **************************************************************************************************
    1974      8740881 :    SUBROUTINE dbt_permute_index(tensor_in, tensor_out, order)
    1975              :       TYPE(dbt_type), INTENT(INOUT)                  :: tensor_in
    1976              :       TYPE(dbt_type), INTENT(OUT)                 :: tensor_out
    1977              :       INTEGER, DIMENSION(ndims_tensor(tensor_in)), &
    1978              :          INTENT(IN)                                   :: order
    1979              : 
    1980      4856045 :       TYPE(nd_to_2d_mapping)                          :: nd_index_blk_rs, nd_index_rs
    1981              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'dbt_permute_index'
    1982              :       INTEGER                                         :: handle
    1983              :       INTEGER                                         :: ndims
    1984              : 
    1985       971209 :       CALL timeset(routineN, handle)
    1986              : 
    1987       971209 :       ndims = ndims_tensor(tensor_in)
    1988              : 
    1989       971209 :       CALL permute_index(tensor_in%nd_index, nd_index_rs, order)
    1990       971209 :       CALL permute_index(tensor_in%nd_index_blk, nd_index_blk_rs, order)
    1991       971209 :       CALL permute_index(tensor_in%pgrid%nd_index_grid, tensor_out%pgrid%nd_index_grid, order)
    1992              : 
    1993       971209 :       tensor_out%matrix_rep => tensor_in%matrix_rep
    1994       971209 :       tensor_out%owns_matrix = .FALSE.
    1995              : 
    1996       971209 :       tensor_out%nd_index = nd_index_rs
    1997       971209 :       tensor_out%nd_index_blk = nd_index_blk_rs
    1998       971209 :       tensor_out%pgrid%mp_comm_2d = tensor_in%pgrid%mp_comm_2d
    1999       971209 :       IF (ALLOCATED(tensor_in%pgrid%tas_split_info)) THEN
    2000       971209 :          ALLOCATE (tensor_out%pgrid%tas_split_info, SOURCE=tensor_in%pgrid%tas_split_info)
    2001              :       END IF
    2002       971209 :       tensor_out%refcount => tensor_in%refcount
    2003       971209 :       CALL dbt_hold(tensor_out)
    2004              : 
    2005       971209 :       CALL reorder_arrays(tensor_in%blk_sizes, tensor_out%blk_sizes, order)
    2006       971209 :       CALL reorder_arrays(tensor_in%blk_offsets, tensor_out%blk_offsets, order)
    2007       971209 :       CALL reorder_arrays(tensor_in%nd_dist, tensor_out%nd_dist, order)
    2008       971209 :       CALL reorder_arrays(tensor_in%blks_local, tensor_out%blks_local, order)
    2009      2913627 :       ALLOCATE (tensor_out%nblks_local(ndims))
    2010      1942418 :       ALLOCATE (tensor_out%nfull_local(ndims))
    2011      3555895 :       tensor_out%nblks_local(order) = tensor_in%nblks_local(:)
    2012      3555895 :       tensor_out%nfull_local(order) = tensor_in%nfull_local(:)
    2013       971209 :       tensor_out%name = tensor_in%name
    2014       971209 :       tensor_out%valid = .TRUE.
    2015              : 
    2016       971209 :       IF (ALLOCATED(tensor_in%contraction_storage)) THEN
    2017       423257 :          ALLOCATE (tensor_out%contraction_storage, SOURCE=tensor_in%contraction_storage)
    2018       423257 :          CALL destroy_array_list(tensor_out%contraction_storage%batch_ranges)
    2019       423257 :          CALL reorder_arrays(tensor_in%contraction_storage%batch_ranges, tensor_out%contraction_storage%batch_ranges, order)
    2020              :       END IF
    2021              : 
    2022       971209 :       CALL timestop(handle)
    2023      1942418 :    END SUBROUTINE dbt_permute_index
    2024              : 
    2025              : ! **************************************************************************************************
    2026              : !> \brief Map contraction bounds to bounds referring to tensor indices
    2027              : !>        see dbt_contract for docu of dummy arguments
    2028              : !> \param bounds_t1 bounds mapped to tensor_1
    2029              : !> \param bounds_t2 bounds mapped to tensor_2
    2030              : !> \param do_crop_1 whether tensor 1 should be cropped
    2031              : !> \param do_crop_2 whether tensor 2 should be cropped
    2032              : !> \author Patrick Seewald
    2033              : ! **************************************************************************************************
    2034       292855 :    SUBROUTINE dbt_map_bounds_to_tensors(tensor_1, tensor_2, &
    2035       292855 :                                         contract_1, notcontract_1, &
    2036       585710 :                                         contract_2, notcontract_2, &
    2037       292855 :                                         bounds_t1, bounds_t2, &
    2038       192418 :                                         bounds_1, bounds_2, bounds_3, &
    2039              :                                         do_crop_1, do_crop_2)
    2040              : 
    2041              :       TYPE(dbt_type), INTENT(IN)      :: tensor_1, tensor_2
    2042              :       INTEGER, DIMENSION(:), INTENT(IN)   :: contract_1, contract_2, &
    2043              :                                              notcontract_1, notcontract_2
    2044              :       INTEGER, DIMENSION(2, ndims_tensor(tensor_1)), &
    2045              :          INTENT(OUT)                                 :: bounds_t1
    2046              :       INTEGER, DIMENSION(2, ndims_tensor(tensor_2)), &
    2047              :          INTENT(OUT)                                 :: bounds_t2
    2048              :       INTEGER, DIMENSION(2, SIZE(contract_1)), &
    2049              :          INTENT(IN), OPTIONAL                        :: bounds_1
    2050              :       INTEGER, DIMENSION(2, SIZE(notcontract_1)), &
    2051              :          INTENT(IN), OPTIONAL                        :: bounds_2
    2052              :       INTEGER, DIMENSION(2, SIZE(notcontract_2)), &
    2053              :          INTENT(IN), OPTIONAL                        :: bounds_3
    2054              :       LOGICAL, INTENT(OUT), OPTIONAL                 :: do_crop_1, do_crop_2
    2055              :       LOGICAL, DIMENSION(2)                          :: do_crop
    2056              : 
    2057       292855 :       do_crop = .FALSE.
    2058              : 
    2059      1041211 :       bounds_t1(1, :) = 1
    2060      1041211 :       CALL dbt_get_info(tensor_1, nfull_total=bounds_t1(2, :))
    2061              : 
    2062      1102822 :       bounds_t2(1, :) = 1
    2063      1102822 :       CALL dbt_get_info(tensor_2, nfull_total=bounds_t2(2, :))
    2064              : 
    2065       292855 :       IF (PRESENT(bounds_1)) THEN
    2066       304934 :          bounds_t1(:, contract_1) = bounds_1
    2067       134038 :          do_crop(1) = .TRUE.
    2068       304934 :          bounds_t2(:, contract_2) = bounds_1
    2069       292855 :          do_crop(2) = .TRUE.
    2070              :       END IF
    2071              : 
    2072       292855 :       IF (PRESENT(bounds_2)) THEN
    2073       360162 :          bounds_t1(:, notcontract_1) = bounds_2
    2074       292855 :          do_crop(1) = .TRUE.
    2075              :       END IF
    2076              : 
    2077       292855 :       IF (PRESENT(bounds_3)) THEN
    2078       394598 :          bounds_t2(:, notcontract_2) = bounds_3
    2079       292855 :          do_crop(2) = .TRUE.
    2080              :       END IF
    2081              : 
    2082       292855 :       IF (PRESENT(do_crop_1)) do_crop_1 = do_crop(1)
    2083       292855 :       IF (PRESENT(do_crop_2)) do_crop_2 = do_crop(2)
    2084              : 
    2085       660542 :    END SUBROUTINE dbt_map_bounds_to_tensors
    2086              : 
    2087              : ! **************************************************************************************************
    2088              : !> \brief print tensor contraction indices in a human readable way
    2089              : !> \param indchar1 characters printed for index of tensor 1
    2090              : !> \param indchar2 characters printed for index of tensor 2
    2091              : !> \param indchar3 characters printed for index of tensor 3
    2092              : !> \param unit_nr output unit
    2093              : !> \author Patrick Seewald
    2094              : ! **************************************************************************************************
    2095       221868 :    SUBROUTINE dbt_print_contraction_index(tensor_1, indchar1, tensor_2, indchar2, tensor_3, indchar3, unit_nr)
    2096              :       TYPE(dbt_type), INTENT(IN) :: tensor_1, tensor_2, tensor_3
    2097              :       CHARACTER(LEN=1), DIMENSION(ndims_tensor(tensor_1)), INTENT(IN) :: indchar1
    2098              :       CHARACTER(LEN=1), DIMENSION(ndims_tensor(tensor_2)), INTENT(IN) :: indchar2
    2099              :       CHARACTER(LEN=1), DIMENSION(ndims_tensor(tensor_3)), INTENT(IN) :: indchar3
    2100              :       INTEGER, INTENT(IN) :: unit_nr
    2101       443736 :       INTEGER, DIMENSION(ndims_matrix_row(tensor_1)) :: map11
    2102       443736 :       INTEGER, DIMENSION(ndims_matrix_column(tensor_1)) :: map12
    2103       443736 :       INTEGER, DIMENSION(ndims_matrix_row(tensor_2)) :: map21
    2104       443736 :       INTEGER, DIMENSION(ndims_matrix_column(tensor_2)) :: map22
    2105       443736 :       INTEGER, DIMENSION(ndims_matrix_row(tensor_3)) :: map31
    2106       443736 :       INTEGER, DIMENSION(ndims_matrix_column(tensor_3)) :: map32
    2107              :       INTEGER :: ichar1, ichar2, ichar3, unit_nr_prv
    2108              : 
    2109       221868 :       unit_nr_prv = prep_output_unit(unit_nr)
    2110              : 
    2111       221868 :       IF (unit_nr_prv /= 0) THEN
    2112       221868 :          CALL dbt_get_mapping_info(tensor_1%nd_index_blk, map1_2d=map11, map2_2d=map12)
    2113       221868 :          CALL dbt_get_mapping_info(tensor_2%nd_index_blk, map1_2d=map21, map2_2d=map22)
    2114       221868 :          CALL dbt_get_mapping_info(tensor_3%nd_index_blk, map1_2d=map31, map2_2d=map32)
    2115              :       END IF
    2116              : 
    2117       221868 :       IF (unit_nr_prv > 0) THEN
    2118           30 :          WRITE (unit_nr_prv, '(T2,A)') "INDEX INFO"
    2119           30 :          WRITE (unit_nr_prv, '(T15,A)', advance='no') "tensor index: ("
    2120          123 :          DO ichar1 = 1, SIZE(indchar1)
    2121          123 :             WRITE (unit_nr_prv, '(A1)', advance='no') indchar1(ichar1)
    2122              :          END DO
    2123           30 :          WRITE (unit_nr_prv, '(A)', advance='no') ") x ("
    2124          120 :          DO ichar2 = 1, SIZE(indchar2)
    2125          120 :             WRITE (unit_nr_prv, '(A1)', advance='no') indchar2(ichar2)
    2126              :          END DO
    2127           30 :          WRITE (unit_nr_prv, '(A)', advance='no') ") = ("
    2128          123 :          DO ichar3 = 1, SIZE(indchar3)
    2129          123 :             WRITE (unit_nr_prv, '(A1)', advance='no') indchar3(ichar3)
    2130              :          END DO
    2131           30 :          WRITE (unit_nr_prv, '(A)') ")"
    2132              : 
    2133           30 :          WRITE (unit_nr_prv, '(T15,A)', advance='no') "matrix index: ("
    2134           82 :          DO ichar1 = 1, SIZE(map11)
    2135           82 :             WRITE (unit_nr_prv, '(A1)', advance='no') indchar1(map11(ichar1))
    2136              :          END DO
    2137           30 :          WRITE (unit_nr_prv, '(A1)', advance='no') "|"
    2138           71 :          DO ichar1 = 1, SIZE(map12)
    2139           71 :             WRITE (unit_nr_prv, '(A1)', advance='no') indchar1(map12(ichar1))
    2140              :          END DO
    2141           30 :          WRITE (unit_nr_prv, '(A)', advance='no') ") x ("
    2142           76 :          DO ichar2 = 1, SIZE(map21)
    2143           76 :             WRITE (unit_nr_prv, '(A1)', advance='no') indchar2(map21(ichar2))
    2144              :          END DO
    2145           30 :          WRITE (unit_nr_prv, '(A1)', advance='no') "|"
    2146           74 :          DO ichar2 = 1, SIZE(map22)
    2147           74 :             WRITE (unit_nr_prv, '(A1)', advance='no') indchar2(map22(ichar2))
    2148              :          END DO
    2149           30 :          WRITE (unit_nr_prv, '(A)', advance='no') ") = ("
    2150           79 :          DO ichar3 = 1, SIZE(map31)
    2151           79 :             WRITE (unit_nr_prv, '(A1)', advance='no') indchar3(map31(ichar3))
    2152              :          END DO
    2153           30 :          WRITE (unit_nr_prv, '(A1)', advance='no') "|"
    2154           74 :          DO ichar3 = 1, SIZE(map32)
    2155           74 :             WRITE (unit_nr_prv, '(A1)', advance='no') indchar3(map32(ichar3))
    2156              :          END DO
    2157           30 :          WRITE (unit_nr_prv, '(A)') ")"
    2158              :       END IF
    2159              : 
    2160       221868 :    END SUBROUTINE dbt_print_contraction_index
    2161              : 
    2162              : ! **************************************************************************************************
    2163              : !> \brief Initialize batched contraction for this tensor.
    2164              : !>
    2165              : !>        Explanation: A batched contraction is a contraction performed in several consecutive steps
    2166              : !>        by specification of bounds in dbt_contract. This can be used to reduce memory by
    2167              : !>        a large factor. The routines dbt_batched_contract_init and
    2168              : !>        dbt_batched_contract_finalize should be called to define the scope of a batched
    2169              : !>        contraction as this enables important optimizations (adapting communication scheme to
    2170              : !>        batches and adapting process grid to multiplication algorithm). The routines
    2171              : !>        dbt_batched_contract_init and dbt_batched_contract_finalize must be
    2172              : !>        called before the first and after the last contraction step on all 3 tensors.
    2173              : !>
    2174              : !>        Requirements:
    2175              : !>        - the tensors are in a compatible matrix layout (see documentation of
    2176              : !>          `dbt_contract`, note 2 & 3). If they are not, process grid optimizations are
    2177              : !>          disabled and a warning is issued.
    2178              : !>        - within the scope of a batched contraction, it is not allowed to access or change tensor
    2179              : !>          data except by calling dbt_contract, dbt_copy, or the tensor-array form of dbt_copy_indexed.
    2180              : !>        - the bounds affecting indices of the smallest tensor must not change in the course of a
    2181              : !>          batched contraction (todo: get rid of this requirement).
    2182              : !>
    2183              : !>        Side effects:
    2184              : !>        - the parallel layout (process grid and distribution) of all tensors may change. In order
    2185              : !>          to disable the process grid optimization including this side effect, call this routine
    2186              : !>          only on the smallest of the 3 tensors.
    2187              : !>
    2188              : !> \note
    2189              : !>        Note 1: for an example of batched contraction see `examples/dbt_example.F`.
    2190              : !>        (todo: the example is outdated and should be updated).
    2191              : !>
    2192              : !>        Note 2: it is meaningful to use this feature if the contraction consists of one batch only
    2193              : !>        but if multiple contractions involving the same 3 tensors are performed
    2194              : !>        (batched_contract_init and batched_contract_finalize must then be called before/after each
    2195              : !>        contraction call). The process grid is then optimized after the first contraction
    2196              : !>        and future contraction may profit from this optimization.
    2197              : !>
    2198              : !> \param batch_range_i refers to the ith tensor dimension and contains all block indices starting
    2199              : !>                      a new range. The size should be the number of ranges plus one, the last
    2200              : !>                      element being the block index plus one of the last block in the last range.
    2201              : !>                      For internal load balancing optimizations, optionally specify the index
    2202              : !>                      ranges of batched contraction.
    2203              : !> \author Patrick Seewald
    2204              : ! **************************************************************************************************
    2205       166859 :    SUBROUTINE dbt_batched_contract_init(tensor, ${varlist("batch_range")}$)
    2206              :       TYPE(dbt_type), INTENT(INOUT) :: tensor
    2207              :       INTEGER, DIMENSION(:), OPTIONAL, INTENT(IN)        :: ${varlist("batch_range")}$
    2208       333718 :       INTEGER, DIMENSION(ndims_tensor(tensor)) :: tdims
    2209       166859 :       INTEGER, DIMENSION(:), ALLOCATABLE                 :: ${varlist("batch_range_prv")}$
    2210              :       LOGICAL :: static_range
    2211              : 
    2212       166859 :       CALL dbt_get_info(tensor, nblks_total=tdims)
    2213              : 
    2214       166859 :       static_range = .TRUE.
    2215              :       #:for idim in range(1, maxdim+1)
    2216       166859 :          IF (ndims_tensor(tensor) >= ${idim}$) THEN
    2217       392108 :             IF (PRESENT(batch_range_${idim}$)) THEN
    2218       589852 :                ALLOCATE (batch_range_prv_${idim}$, source=batch_range_${idim}$)
    2219       392108 :                static_range = .FALSE.
    2220              :             ELSE
    2221       303948 :                ALLOCATE (batch_range_prv_${idim}$ (2))
    2222       303948 :                batch_range_prv_${idim}$ (1) = 1
    2223       303948 :                batch_range_prv_${idim}$ (2) = tdims(${idim}$) + 1
    2224              :             END IF
    2225              :          END IF
    2226              :       #:endfor
    2227              : 
    2228       166859 :       ALLOCATE (tensor%contraction_storage)
    2229       166859 :       tensor%contraction_storage%static = static_range
    2230       166859 :       IF (static_range) THEN
    2231       115567 :          CALL dbt_tas_batched_mm_init(tensor%matrix_rep)
    2232              :       END IF
    2233       166859 :       tensor%contraction_storage%nsplit_avg = 0.0_dp
    2234       166859 :       tensor%contraction_storage%ibatch = 0
    2235              : 
    2236              :       #:for ndim in range(1, maxdim+1)
    2237       333718 :          IF (ndims_tensor(tensor) == ${ndim}$) THEN
    2238              :             CALL create_array_list(tensor%contraction_storage%batch_ranges, ${ndim}$, &
    2239       166859 :                                    ${varlist("batch_range_prv", nmax=ndim)}$)
    2240              :          END IF
    2241              :       #:endfor
    2242              : 
    2243       166859 :    END SUBROUTINE dbt_batched_contract_init
    2244              : 
    2245              : ! **************************************************************************************************
    2246              : !> \brief finalize batched contraction. This performs all communication that has been postponed in
    2247              : !>         the contraction calls.
    2248              : !> \author Patrick Seewald
    2249              : ! **************************************************************************************************
    2250       166859 :    SUBROUTINE dbt_batched_contract_finalize(tensor, unit_nr)
    2251              :       TYPE(dbt_type), INTENT(INOUT) :: tensor
    2252              :       INTEGER, INTENT(IN), OPTIONAL :: unit_nr
    2253              :       LOGICAL :: do_write
    2254              :       INTEGER :: unit_nr_prv, handle
    2255              : 
    2256       166859 :       CALL timeset("dbt_total", handle)
    2257       166859 :       unit_nr_prv = prep_output_unit(unit_nr)
    2258              : 
    2259       166859 :       do_write = .FALSE.
    2260              : 
    2261       166859 :       IF (tensor%contraction_storage%static) THEN
    2262       115567 :          IF (tensor%matrix_rep%do_batched > 0) THEN
    2263       115567 :             IF (tensor%matrix_rep%mm_storage%batched_out) do_write = .TRUE.
    2264              :          END IF
    2265       115567 :          CALL dbt_tas_batched_mm_finalize(tensor%matrix_rep)
    2266              :       END IF
    2267              : 
    2268       166859 :       IF (do_write .AND. unit_nr_prv /= 0) THEN
    2269        24010 :          IF (unit_nr_prv > 0) THEN
    2270              :             WRITE (unit_nr_prv, "(T2,A)") &
    2271            0 :                "FINALIZING BATCHED PROCESSING OF MATMUL"
    2272              :          END IF
    2273        24010 :          CALL dbt_write_tensor_info(tensor, unit_nr_prv)
    2274        24010 :          CALL dbt_write_tensor_dist(tensor, unit_nr_prv)
    2275              :       END IF
    2276              : 
    2277       166859 :       CALL destroy_array_list(tensor%contraction_storage%batch_ranges)
    2278       166859 :       DEALLOCATE (tensor%contraction_storage)
    2279       166859 :       CALL timestop(handle)
    2280              : 
    2281       166859 :    END SUBROUTINE dbt_batched_contract_finalize
    2282              : 
    2283              : ! **************************************************************************************************
    2284              : !> \brief change the process grid of a tensor
    2285              : !> \param nodata optionally don't copy the tensor data (then tensor is empty on returned)
    2286              : !> \param batch_range_i refers to the ith tensor dimension and contains all block indices starting
    2287              : !>                      a new range. The size should be the number of ranges plus one, the last
    2288              : !>                      element being the block index plus one of the last block in the last range.
    2289              : !>                      For internal load balancing optimizations, optionally specify the index
    2290              : !>                      ranges of batched contraction.
    2291              : !> \author Patrick Seewald
    2292              : ! **************************************************************************************************
    2293          964 :    SUBROUTINE dbt_change_pgrid(tensor, pgrid, ${varlist("batch_range")}$, &
    2294              :                                nodata, pgrid_changed, unit_nr)
    2295              :       TYPE(dbt_type), INTENT(INOUT)                  :: tensor
    2296              :       TYPE(dbt_pgrid_type), INTENT(IN)               :: pgrid
    2297              :       INTEGER, DIMENSION(:), OPTIONAL, INTENT(IN)        :: ${varlist("batch_range")}$
    2298              :       !!
    2299              :       LOGICAL, INTENT(IN), OPTIONAL                      :: nodata
    2300              :       LOGICAL, INTENT(OUT), OPTIONAL                     :: pgrid_changed
    2301              :       INTEGER, INTENT(IN), OPTIONAL                      :: unit_nr
    2302              :       CHARACTER(LEN=*), PARAMETER :: routineN = 'dbt_change_pgrid'
    2303              :       CHARACTER(default_string_length)                   :: name
    2304              :       INTEGER                                            :: handle
    2305          964 :       INTEGER, ALLOCATABLE, DIMENSION(:)                 :: ${varlist("bs")}$, &
    2306          964 :                                                             ${varlist("dist")}$
    2307         1928 :       INTEGER, DIMENSION(ndims_tensor(tensor))           :: pcoord, pcoord_ref, pdims, pdims_ref, &
    2308         1928 :                                                             tdims
    2309         6748 :       TYPE(dbt_type)                                 :: t_tmp
    2310         6748 :       TYPE(dbt_distribution_type)                    :: dist
    2311         1928 :       INTEGER, DIMENSION(ndims_matrix_row(tensor)) :: map1
    2312              :       INTEGER, &
    2313         1928 :          DIMENSION(ndims_matrix_column(tensor))    :: map2
    2314         1928 :       LOGICAL, DIMENSION(ndims_tensor(tensor))             :: mem_aware
    2315          964 :       INTEGER, DIMENSION(ndims_tensor(tensor)) :: nbatch
    2316              :       INTEGER :: ind1, ind2, batch_size, ibatch
    2317              : 
    2318          964 :       IF (PRESENT(pgrid_changed)) pgrid_changed = .FALSE.
    2319          964 :       CALL mp_environ_pgrid(pgrid, pdims, pcoord)
    2320          964 :       CALL mp_environ_pgrid(tensor%pgrid, pdims_ref, pcoord_ref)
    2321              : 
    2322          988 :       IF (ALL(pdims == pdims_ref)) THEN
    2323            8 :          IF (ALLOCATED(pgrid%tas_split_info) .AND. ALLOCATED(tensor%pgrid%tas_split_info)) THEN
    2324            8 :             IF (pgrid%tas_split_info%ngroup == tensor%pgrid%tas_split_info%ngroup) THEN
    2325              :                RETURN
    2326              :             END IF
    2327              :          END IF
    2328              :       END IF
    2329              : 
    2330          956 :       CALL timeset(routineN, handle)
    2331              : 
    2332              :       #:for idim in range(1, maxdim+1)
    2333         3824 :          IF (ndims_tensor(tensor) >= ${idim}$) THEN
    2334         2868 :             mem_aware(${idim}$) = PRESENT(batch_range_${idim}$)
    2335         2868 :             IF (mem_aware(${idim}$)) nbatch(${idim}$) = SIZE(batch_range_${idim}$) - 1
    2336              :          END IF
    2337              :       #:endfor
    2338              : 
    2339          956 :       CALL dbt_get_info(tensor, nblks_total=tdims, name=name)
    2340              : 
    2341              :       #:for idim in range(1, maxdim+1)
    2342         3824 :          IF (ndims_tensor(tensor) >= ${idim}$) THEN
    2343         8604 :             ALLOCATE (bs_${idim}$ (dbt_nblks_total(tensor, ${idim}$)))
    2344         2868 :             CALL get_ith_array(tensor%blk_sizes, ${idim}$, bs_${idim}$)
    2345         8604 :             ALLOCATE (dist_${idim}$ (tdims(${idim}$)))
    2346         2868 :             dist_${idim}$ = 0
    2347         2868 :             IF (mem_aware(${idim}$)) THEN
    2348         8456 :                DO ibatch = 1, nbatch(${idim}$)
    2349         5588 :                   ind1 = batch_range_${idim}$ (ibatch)
    2350         5588 :                   ind2 = batch_range_${idim}$ (ibatch + 1) - 1
    2351         5588 :                   batch_size = ind2 - ind1 + 1
    2352              :                   CALL dbt_default_distvec(batch_size, pdims(${idim}$), &
    2353         8456 :                                            bs_${idim}$ (ind1:ind2), dist_${idim}$ (ind1:ind2))
    2354              :                END DO
    2355              :             ELSE
    2356            0 :                CALL dbt_default_distvec(tdims(${idim}$), pdims(${idim}$), bs_${idim}$, dist_${idim}$)
    2357              :             END IF
    2358              :          END IF
    2359              :       #:endfor
    2360              : 
    2361          956 :       CALL dbt_get_mapping_info(tensor%nd_index_blk, map1_2d=map1, map2_2d=map2)
    2362              :       #:for ndim in ndims
    2363         1912 :          IF (ndims_tensor(tensor) == ${ndim}$) THEN
    2364          956 :             CALL dbt_distribution_new(dist, pgrid, ${varlist("dist", nmax=ndim)}$)
    2365          956 :             CALL dbt_create(t_tmp, name, dist, map1, map2, ${varlist("bs", nmax=ndim)}$)
    2366              :          END IF
    2367              :       #:endfor
    2368          956 :       CALL dbt_distribution_destroy(dist)
    2369              : 
    2370          956 :       IF (PRESENT(nodata)) THEN
    2371            0 :          IF (.NOT. nodata) CALL dbt_copy_expert(tensor, t_tmp, move_data=.TRUE.)
    2372              :       ELSE
    2373          956 :          CALL dbt_copy_expert(tensor, t_tmp, move_data=.TRUE.)
    2374              :       END IF
    2375              : 
    2376          956 :       CALL dbt_copy_contraction_storage(tensor, t_tmp)
    2377              : 
    2378          956 :       CALL dbt_destroy(tensor)
    2379          956 :       tensor = t_tmp
    2380              : 
    2381          956 :       IF (PRESENT(unit_nr)) THEN
    2382          956 :          IF (unit_nr > 0) THEN
    2383            0 :             WRITE (unit_nr, "(T2,A,1X,A)") "OPTIMIZED PGRID INFO FOR", TRIM(tensor%name)
    2384            0 :             WRITE (unit_nr, "(T4,A,1X,3I6)") "process grid dimensions:", pdims
    2385            0 :             CALL dbt_write_split_info(pgrid, unit_nr)
    2386              :          END IF
    2387              :       END IF
    2388              : 
    2389          956 :       IF (PRESENT(pgrid_changed)) pgrid_changed = .TRUE.
    2390              : 
    2391          956 :       CALL timestop(handle)
    2392          964 :    END SUBROUTINE dbt_change_pgrid
    2393              : 
    2394              : ! **************************************************************************************************
    2395              : !> \brief map tensor to a new 2d process grid for the matrix representation.
    2396              : !> \author Patrick Seewald
    2397              : ! **************************************************************************************************
    2398          964 :    SUBROUTINE dbt_change_pgrid_2d(tensor, mp_comm, pdims, nodata, nsplit, dimsplit, pgrid_changed, unit_nr)
    2399              :       TYPE(dbt_type), INTENT(INOUT)                  :: tensor
    2400              :       TYPE(mp_cart_type), INTENT(IN)               :: mp_comm
    2401              :       INTEGER, DIMENSION(2), INTENT(IN), OPTIONAL :: pdims
    2402              :       LOGICAL, INTENT(IN), OPTIONAL                      :: nodata
    2403              :       INTEGER, INTENT(IN), OPTIONAL :: nsplit, dimsplit
    2404              :       LOGICAL, INTENT(OUT), OPTIONAL :: pgrid_changed
    2405              :       INTEGER, INTENT(IN), OPTIONAL                      :: unit_nr
    2406         1928 :       INTEGER, DIMENSION(ndims_matrix_row(tensor)) :: map1
    2407         1928 :       INTEGER, DIMENSION(ndims_matrix_column(tensor)) :: map2
    2408         1928 :       INTEGER, DIMENSION(ndims_tensor(tensor)) :: dims, nbatches
    2409         2892 :       TYPE(dbt_pgrid_type) :: pgrid
    2410          964 :       INTEGER, DIMENSION(:), ALLOCATABLE :: ${varlist("batch_range")}$
    2411          964 :       INTEGER, DIMENSION(:), ALLOCATABLE :: array
    2412              :       INTEGER :: idim
    2413              : 
    2414          964 :       CALL dbt_get_mapping_info(tensor%pgrid%nd_index_grid, map1_2d=map1, map2_2d=map2)
    2415          964 :       CALL blk_dims_tensor(tensor, dims)
    2416              : 
    2417          964 :       IF (ALLOCATED(tensor%contraction_storage)) THEN
    2418              :          ASSOCIATE (batch_ranges => tensor%contraction_storage%batch_ranges)
    2419         3856 :             nbatches = sizes_of_arrays(tensor%contraction_storage%batch_ranges) - 1
    2420              :             ! for good load balancing the process grid dimensions should be chosen adapted to the
    2421              :             ! tensor dimenions. For batched contraction the tensor dimensions should be divided by
    2422              :             ! the number of batches (number of index ranges).
    2423         4820 :             DO idim = 1, ndims_tensor(tensor)
    2424         2892 :                CALL get_ith_array(tensor%contraction_storage%batch_ranges, idim, array)
    2425         2892 :                dims(idim) = array(nbatches(idim) + 1) - array(1)
    2426         2892 :                DEALLOCATE (array)
    2427         2892 :                dims(idim) = dims(idim)/nbatches(idim)
    2428         3856 :                IF (dims(idim) <= 0) dims(idim) = 1
    2429              :             END DO
    2430              :          END ASSOCIATE
    2431              :       END IF
    2432              : 
    2433          964 :       pgrid = dbt_nd_mp_comm(mp_comm, map1, map2, pdims_2d=pdims, tdims=dims, nsplit=nsplit, dimsplit=dimsplit)
    2434          964 :       IF (ALLOCATED(tensor%contraction_storage)) THEN
    2435              :          #:for ndim in range(1, maxdim+1)
    2436         1928 :             IF (ndims_tensor(tensor) == ${ndim}$) THEN
    2437          964 :                CALL get_arrays(tensor%contraction_storage%batch_ranges, ${varlist("batch_range", nmax=ndim)}$)
    2438              :                CALL dbt_change_pgrid(tensor, pgrid, ${varlist("batch_range", nmax=ndim)}$, &
    2439          964 :                                      nodata=nodata, pgrid_changed=pgrid_changed, unit_nr=unit_nr)
    2440              :             END IF
    2441              :          #:endfor
    2442              :       ELSE
    2443            0 :          CALL dbt_change_pgrid(tensor, pgrid, nodata=nodata, pgrid_changed=pgrid_changed, unit_nr=unit_nr)
    2444              :       END IF
    2445          964 :       CALL dbt_pgrid_destroy(pgrid)
    2446              : 
    2447          964 :    END SUBROUTINE dbt_change_pgrid_2d
    2448              : 
    2449        82171 : END MODULE dbt_methods
        

Generated by: LCOV version 2.0-1