From 6be7a99811da36794694a5e9579f6007199bce12 Mon Sep 17 00:00:00 2001 From: julpe Date: Wed, 2 Dec 2026 14:09:47 +0100 Subject: [PATCH] Stream bubble shells and refine memory estimates --- .gitignore | 1 + dgamore/DGAmore.py | 4 + dgamore/bubble_gen.py | 55 ++++++-------- dgamore/eliashberg_solver.py | 31 +++++--- dgamore/memory_estimator.py | 97 +++++++++++++++++------- pyproject.toml | 1 + tests/test_autodetect_memory.py | 11 ++- tests/test_bubble_gen.py | 24 ++++++ tests/test_eliashberg_solver.py | 14 +++- tests/test_local_sde.py | 2 + tests/test_memory_estimator.py | 126 ++++++++++++++++++++++++++------ 11 files changed, 267 insertions(+), 99 deletions(-) diff --git a/.gitignore b/.gitignore index d5c8fadf..2be10816 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ tests/**/*.hdf5 .idea/ .vscode/ .claude/ +.codex/ .superpowers/ # other diff --git a/dgamore/DGAmore.py b/dgamore/DGAmore.py index 8a0165ac..b59ea527 100644 --- a/dgamore/DGAmore.py +++ b/dgamore/DGAmore.py @@ -773,6 +773,8 @@ def counts(rank: int) -> tuple[int, int, int, int]: groups.setdefault(counts(rank), [rank, 0])[1] += 1 node_groups.append((list(groups.values()), 0 in ranks, avail * NODE_MEMORY_FRACTION)) + # the momentum maps of the point group, which every rank builds in the self-energy step anyway + point_group = config.lattice.k_grid.auto_point_group() niv_pp = min(config.box.niw_core // 2, config.box.niv_core // 2) # Must mirror the giwk_full window the SDE section starts from in nonlocal_sde.calculate_self_energy_q. niv_cut = min(config.box.niw_core + config.box.niv_full + 10, config.box.niv_dmft) @@ -807,6 +809,8 @@ def counts(rank: int) -> tuple[int, int, int, int]: warm_start=bool(config.self_consistency.previous_sc_path), previous_proposal=config.self_consistency.max_iter > 1, with_jacobian_tracker=config.stabilization.use_jacobian_stabilization, + n_symmetries=len(config.lattice.k_grid._auto_group or ()), + n_point_operations=0 if point_group is None else len(point_group[0]), ) # the estimates of this call, keyed by the counts, the budgets and the exact-Jacobian flag, which can be disabled estimates: dict = {} diff --git a/dgamore/bubble_gen.py b/dgamore/bubble_gen.py index 6b4dace5..c6633ddc 100644 --- a/dgamore/bubble_gen.py +++ b/dgamore/bubble_gen.py @@ -189,7 +189,7 @@ def create_generalized_chi0_q_fft( g_flat = np.reshape(g_r.mat, (k_grid.nk_tot, nb * nb, -1)) rev = BubbleGenerator._reversed_momenta(k_grid.nk) pair_products = BubbleGenerator._pair_products(nb, None if components is None else components[0]) - sums = np.zeros((len(k_grid.irrk_ind), nb**4, len(wn), len(pieces)), dtype=g_r.mat.dtype) + sums = np.zeros((len(k_grid.irrk_ind), nb**4, len(wn)), dtype=g_r.mat.dtype) summed = np.empty((k_grid.nk_tot, len(pair_products)), dtype=g_r.mat.dtype) g_r = np.asarray(g_r.mat[..., start:end], order="C") g_r_rev = np.asarray(g_r_rev.mat, order="C") @@ -223,19 +223,20 @@ def create_generalized_chi0_q_fft( if found.any(): crossed = np.conj(gchi0_q_mat[..., iw, :n_v][..., found].transpose(0, 3, 4, 1, 2, 5)) gchi0_q_mat[..., iw, partners[mine][found] % (2 * n_keep)] = crossed - for p, piece in enumerate(pieces): + for piece in pieces: BubbleGenerator._sum_column_products(summed, g_flat, rev, start + piece, wn_i, pair_products) rows = sp.fft.ifftn(summed.reshape(*k_grid.nk, -1), axes=(0, 1, 2), overwrite_x=True) rows = rows.reshape(k_grid.nk_tot, -1)[k_grid.irrk_ind] if components is None: - sums[:, :, iw, p] = rows + sums[:, :, iw] += rows else: - sums[:, components[0], iw, p], sums[:, components[1], iw, p] = rows, rows[:, components[2]] + sums[:, components[0], iw] += rows + sums[:, components[1], iw] += rows[:, components[2]] gchi0_q_mat *= -beta / k_grid.nk_tot if pieces: - shell_mat = BubbleGenerator._add_pieces(sums, beta, k_grid.nk_tot) - shell_mat = shell_mat.reshape(len(k_grid.irrk_ind), nb, nb, nb, nb, len(wn)) + sums *= -beta / k_grid.nk_tot + shell_mat = sums.reshape(len(k_grid.irrk_ind), nb, nb, nb, nb, len(wn)) gchi0_q_mat = mpi_dist_irrk.scatter(gchi0_q_mat) bubble = FourPoint( @@ -417,22 +418,6 @@ def _sum_column_products( product[:n] += term[:n] out[r0 : r0 + n] = product[:n].reshape(n, -1)[:, pairs] - @staticmethod - def _add_pieces(sums: np.ndarray, beta: float, nk_tot: int) -> np.ndarray: - r""" - Returns the sum of the transformed pieces of summed columns, added in their order and scaled as the bubble. - - :param sums: The transformed pieces on the last axis, ``[..., n_pieces]``. - :param beta: Inverse temperature :math:`\beta`. - :param nk_tot: Number of momenta of the grid. - :return: The scaled sum ``[...]``. - """ - total = sums[..., 0].copy() - for p in range(1, sums.shape[-1]): - total += sums[..., p] - total *= -beta / nk_tot - return total - @staticmethod def _add_product(out: np.ndarray, left: np.ndarray, right: np.ndarray, block: np.ndarray) -> None: """ @@ -546,8 +531,9 @@ def _create_generalized_chi0_q_fft_distributed( :meth:`_summed_pieces`): a piece is one more column of its bosonic frequency, filled with the summed products of all its components at once (see :meth:`_sum_column_products`; that buffer of one full-grid column of every component is held from a rank's first piece to its first core column), and transformed and exchanged - as a column is. The pieces come first in the schedule, so the rounds that hold them hold little else, and each - is stored on its own until all have arrived and are added in their order. + as a column is. The pieces run first, one pass per piece of every bosonic frequency, so each arrives after the + one before it and is added to its frequency's sum at once: a rank stores one sum per bosonic frequency, not + every piece. :param mpi_dist_irrk: MPI distributor over the irreducible BZ q-points (see :class:`MpiDistributor`). :param giwk: The momentum-dependent :class:`GreensFunction`. @@ -603,8 +589,8 @@ def build_g_r() -> np.ndarray: # contiguous, columns w-major; one stored bosonic frequency per array with blocks width = 2 * n_keep if blocks else len(wn) * 2 * n_keep mat_cols = [np.reshape(mat, (my_nq, nb**4, width), copy=False) for mat in mats] - # the transformed pieces of every bosonic frequency, each on its own until they are added in their order - sums = [np.empty((my_nq, nb**4, n_sum), dtype=g_r_mat.dtype) for _ in wn] if n_sum else [] + # one sum of the transformed pieces per bosonic frequency + sums = [np.zeros((my_nq, nb**4), dtype=g_r_mat.dtype) for _ in wn] if n_sum else [] # chi0_1234(R) = G_14(R) G_32(-R): the flat factor pairs of every transformed component, the orbital swap # of the partner, and the column's two factors, orbital-major, gathered once per column @@ -650,7 +636,8 @@ def put(target: slice, values: np.ndarray) -> None: kept columns, or subtracts them (``subtract_from``).""" iw, first = divmod(target.start, vpos) if first < n_sum: - sums[iw][:, :, first : first + target.stop - target.start] = values + # a pass holds one piece per bosonic frequency, so the pieces are added in their order + sums[iw] += values[..., 0] return kept = iw * 2 * n_keep + first - n_sum b = kept // width @@ -701,15 +688,16 @@ def column(kept: np.ndarray) -> np.ndarray: kept, partners = BubbleGenerator._crossing_columns(wn, n_keep) partner_of = np.full(len(wn) * vpos, -1) partner_of[column(kept)] = np.where(partners >= 0, column(partners), -1) - # every piece before the first kept column - columns = np.concatenate(((np.arange(len(wn))[:, None] * vpos + np.arange(n_sum)).ravel(), column(kept))) + columns = column(kept) if release is not None: release() comp_shape = (nb,) * 4 if components is None else (len(components[0]),) group = max(1, ROUND_BUFFER_BYTES // (nk_tot * g_r_mat.itemsize)) - BubbleGenerator._run_columns( - mpi_dist_irrk, k_grid, len(wn), vpos, 1, comp_shape, g_r_mat.dtype, fill, deliver, columns, group - ) + # one pass per piece of every bosonic frequency, then the kept columns + for passed in [np.arange(len(wn)) * vpos + p for p in range(n_sum)] + [columns]: + BubbleGenerator._run_columns( + mpi_dist_irrk, k_grid, len(wn), vpos, 1, comp_shape, g_r_mat.dtype, fill, deliver, passed, group + ) g_r_mat = None if g_r_win is not None: node_comm.Barrier() @@ -728,7 +716,8 @@ def column(kept: np.ndarray) -> np.ndarray: return bubbles if blocks else bubbles[0] shells = [] while sums: - total = BubbleGenerator._add_pieces(sums.pop(0), beta, nk_tot).reshape(my_nq, nb, nb, nb, nb, 1) + total = sums.pop(0).reshape(my_nq, nb, nb, nb, nb, 1) + total *= -beta / nk_tot shells.append(FourPoint(total, SpinChannel.NONE, k_grid.nk, 1, 0, False, True, True).filter_small_values()) return bubbles, shells diff --git a/dgamore/eliashberg_solver.py b/dgamore/eliashberg_solver.py index b56df555..4ef7eb66 100644 --- a/dgamore/eliashberg_solver.py +++ b/dgamore/eliashberg_solver.py @@ -2859,6 +2859,25 @@ def _solve_sectors_in_memory( return results +def combine_pairing_vertices(f_dens_pp: FourPoint, f_magn_pp: FourPoint) -> tuple[FourPoint, FourPoint]: + r""" + Returns the singlet and triplet pairing vertices of the density and magnetic full ladder vertices in pp notation, + :math:`\Gamma_{\mathrm{sing}} = \tfrac{1}{2} F_{\mathrm{d}} - \tfrac{3}{2} F_{\mathrm{m}}` and + :math:`\Gamma_{\mathrm{trip}} = \Gamma_{\mathrm{sing}} + 2 F_{\mathrm{m}}`. The singlet vertex is built in the + density vertex and the magnetic vertex is freed, so the step holds three vertices at most. + + :param f_dens_pp: The density full ladder vertex :math:`F_{\mathrm{d}}`; overwritten with the singlet vertex. + :param f_magn_pp: The magnetic full ladder vertex :math:`F_{\mathrm{m}}`; freed. + :return: The pair ``(singlet, triplet)``. + """ + gamma_sing_pp = f_dens_pp.scale(0.5).sub(f_magn_pp.scale(1.5, copy=True), copy=False) + gamma_sing_pp.channel = SpinChannel.SING + gamma_trip_pp = gamma_sing_pp.add(f_magn_pp.scale(2.0)) + gamma_trip_pp.channel = SpinChannel.TRIP + f_magn_pp.free() + return gamma_sing_pp, gamma_trip_pp + + def solve( giwk_dga: GreensFunction | None, g_dmft: GreensFunction, @@ -2975,15 +2994,9 @@ def solve( if comm.rank == 0: output_files.delete_files(config.output.eliashberg_path, f"{output_files.GIWK_FILE_STEM}.npy") - gamma_sing_pp = f_dens_pp.scale(0.5).sub(f_magn_pp.scale(1.5, copy=True), copy=False) - del f_dens_pp - gamma_sing_pp.channel = SpinChannel.SING - logger.info("Calculated full ladder-vertex (singlet) in pp notation.") - - gamma_trip_pp = gamma_sing_pp.add(f_magn_pp.scale(2.0)) - gamma_trip_pp.channel = SpinChannel.TRIP - f_magn_pp.free() - logger.info("Calculated full ladder-vertex (triplet) in pp notation.") + gamma_sing_pp, gamma_trip_pp = combine_pairing_vertices(f_dens_pp, f_magn_pp) + del f_dens_pp, f_magn_pp + logger.info("Calculated full ladder-vertex (singlet and triplet) in pp notation.") if config.misc.bare_vertex: # Eqs. (4.49)-(4.52) with the bare up-down vertex U as the local full vertex and no pp-reducible diagrams: diff --git a/dgamore/memory_estimator.py b/dgamore/memory_estimator.py index f2396116..c0f7fadf 100644 --- a/dgamore/memory_estimator.py +++ b/dgamore/memory_estimator.py @@ -107,9 +107,6 @@ BUBBLE_ROUND_BYTES: int = 4 * 1024**2 # Bytes of received one-column blocks the distributed bubble hands to one deliver call (bubble_gen.DELIVER_BATCH_BYTES) BUBBLE_DELIVER_BYTES: int = 2 * 1024**2 -# Columns outside the core box whose real-space products the bubble sums before one transform -# (bubble_gen.SUMMED_COLUMNS) -BUBBLE_SUMMED_COLUMNS: int = 32 # Momentum groups of a channel's three-leg vertex and kernel (bits do not depend on it) and one group's blocks alive # beside the stage's residents: the in-place vertex's copies (measured 2.0 to 3.6), the kernel's products (3.2 to 3.6). @@ -466,8 +463,8 @@ def column_sde_stream_bytes( def bubble_stored_columns(niv_core: int, niv_full: int) -> int: r""" Returns the fermionic columns per bosonic frequency the loop's bubble holds while it is built: every column of - the full box without a shell; with one the core columns, the transformed pieces of the outer ones (see - :meth:`~dgamore.bubble_gen.BubbleGenerator._summed_pieces`) and their sum. + the full box without a shell; with one the core columns and the sum of the outer ones, which adds each transformed + piece of them (see :meth:`~dgamore.bubble_gen.BubbleGenerator._summed_pieces`) as it arrives. :param niv_core: Number of positive fermionic core frequencies. :param niv_full: Number of positive fermionic full-region frequencies. @@ -475,7 +472,7 @@ def bubble_stored_columns(niv_core: int, niv_full: int) -> int: """ if niv_full <= niv_core: return 2 * niv_full - return 2 * niv_core + _ceil_div(2 * (niv_full - niv_core), BUBBLE_SUMMED_COLUMNS) + 1 + return 2 * niv_core + 1 def bubble_column_bytes(nk_tot: int, nk_irr: int, n_bands: int, n_cols: int, n_q: int, summed: bool = False) -> int: @@ -711,20 +708,41 @@ def rank_counts(nk_irr: int, nk_tot: int, n_ranks: int, rank: int) -> tuple[int, return rank_tasks(nk_irr, n_ranks, rank, spread=True), rank_tasks(nk_tot, n_ranks, rank) -def rank_input_bytes(nk_tot: int, nk_irr: int, n_bands: int, n_orbitals: int) -> int: +def rank_input_bytes( + nk_tot: int, + nk_irr: int, + n_bands: int, + n_orbitals: int, + n_symmetries: int = 0, + with_eliashberg: bool = False, + n_point_operations: int = 0, +) -> int: r""" Returns the bytes of the inputs every rank holds a private copy of for the whole run: from the broadcast configuration the dispersion :math:`\varepsilon_{12}(\mathbf{k})` ``[nk, no, no]`` and the auto-symmetry rotations of the correlated orbitals ``[nk, nb, nb]`` (both complex128) with the int64 momentum maps, and the complex128 - k-resolved occupation of the correlated orbitals ``occ_k`` ``[nk, nb, nb]``. + k-resolved occupation of the correlated orbitals ``occ_k`` ``[nk, nb, nb]``. An auto-discovered symmetry group + adds the int64 grid action of every element ``[n_symmetries, nk]``, the momentum and real-space maps of its point + group ``[n_point_operations, nk]`` where :meth:`~dgamore.brillouin_zone.KGrid.auto_point_group` builds them, and + the module cache of the grid actions (:mod:`dgamore.symmetry_reduction`): the identity's own copy, every element's + with the Eliashberg step. With the Eliashberg step every rank also caches the stars of the grid from the startup + check on (:func:`~dgamore.eliashberg_solver.wedge_window_points`): their int64 order and, on an auto grid, the + complex128 orbital rotation of every grid index ``[nk, nb, nb]``. :param nk_tot: Total number of momentum points (full BZ). :param nk_irr: Number of momentum points in the irreducible BZ. :param n_bands: Number of bands :math:`B`. :param n_orbitals: Number of orbitals of the dispersion, the bands included. + :param n_symmetries: Number of elements of the auto-discovered symmetry group, 0 without one. + :param with_eliashberg: Whether the Eliashberg step runs. + :param n_point_operations: Number of maps of each of the point group's actions, 0 where + :meth:`~dgamore.brillouin_zone.KGrid.auto_point_group` returns None. :return: The bytes. """ - return 16 * nk_tot * (n_orbitals**2 + 2 * n_bands**2) + 33 * nk_tot + 40 * nk_irr + inputs = 16 * nk_tot * (n_orbitals**2 + 2 * n_bands**2) + 33 * nk_tot + 40 * nk_irr + stars = (8 + (16 * n_bands**2 if n_symmetries else 0)) * nk_tot if with_eliashberg else 0 + cached = n_symmetries if with_eliashberg else min(n_symmetries, 1) + return inputs + 8 * nk_tot * (n_symmetries + cached + 2 * n_point_operations) + stars def interaction_bytes(n_bands: int, nk_tot: int, overhead: float = OVERHEAD_FACTOR) -> float: @@ -1015,6 +1033,8 @@ def estimate_peaks( chunk_budgets: ChunkBudgets = ChunkBudgets(), n_orbitals: int | None = None, bare_vertex: bool = False, + n_symmetries: int = 0, + n_point_operations: int = 0, ) -> dict[str, BranchPeak]: r""" Estimates the per-rank peak host-memory (in bytes) of the fast and lean code path of each memory-sensitive @@ -1046,19 +1066,23 @@ def estimate_peaks( Eliashberg branches run after the self-consistency loop with ``sigma_dga`` freed and ``giwk_dga`` on rank 0 only, so their baseline is the per-rank footprint, plus for ``fq`` the node-shared local vertex the Bethe-Salpeter slices are built from (its - ``giwk_shareable``, absent with ``bare_vertex``); the surviving copy is counted in their single-rank slots. The - ``sigma_loop`` branch is the loop's step from the proposal to the next iterate: every node holds the windows of the - previous and of the next iterate, the core rows of the proposal and its shell offset, every rank the history of - its rows and the linear-mixing copies or the accelerated step's copies on them, rank 0 all of these over every - row with the tracker. The ``mu_update`` branch is the chemical-potential update after it: every rank holds two - complex128 Green's-function arrays on its share of the full-BZ momenta, next to the history and the node's window - of the iterate. The ``energies`` branch + ``giwk_shareable``, absent with ``bare_vertex``); the surviving copy is counted in their single-rank slots. Every + rank of ``fq`` holds the finished density pp vertex beside the magnetic build, or the three pp vertices of their + singlet and triplet combination (see :func:`~dgamore.eliashberg_solver.combine_pairing_vertices`). Every stage of + ``chiq_aux`` sits beside the bubble's two frequency sums and the loop's latest physical susceptibility of each + channel. The ``sigma_loop`` branch is the loop's step from the proposal to the next iterate: every node holds the + windows of the previous and of the next iterate, the core rows of the proposal and its shell offset, every rank + the history of its rows and the linear-mixing copies or the accelerated step's copies on them, rank 0 all of + these over every row with the tracker. The ``mu_update`` branch is the chemical-potential update after it: every + rank holds two complex128 Green's-function arrays on its share of the full-BZ momenta, next to the history and the + node's window of the iterate. The ``energies`` branch is the occupation and energy step after it: every rank holds its share's self-energy and Green's function on the DMFT box and the largest of the Dyson, occupation and energy-tail transients of :mod:`dgamore.greens_function` (bounded by its chunk sizes), next to the same residents and rank 0's whole-grid moment-fit window. The ``occupation`` branch is the start of the non-local routine: every rank's fresh-start occupation on its share of the DMFT box (on a warm start its mu - search), with ``do_spectrum_dmft`` rank 0's DMFT lattice Green's function of the whole grid on that box (built + search on its rows of the start on the ``niv_cut`` box, then the occupation of those rows extended onto the DMFT + box), with ``do_spectrum_dmft`` rank 0's DMFT lattice Green's function of the whole grid on that box (built there, and reloaded with its core-box cut after the loop next to ``giwk_dga`` and ``sigma_dga``), and on a warm start rank 0's starting iterate extended onto it. The ``sigma_interp`` branch, present when ``niv_interp`` is set, is the final re-gridding: rank 0 interpolates the irreducible @@ -1137,6 +1161,10 @@ def estimate_peaks( :param bare_vertex: Whether a bare-vertex mode runs (``config.misc.bare_vertex``), whose pairing-vertex chunks are the RPA vertex of the physical susceptibility: ``"fq"`` then holds no local vertex, one-fermion inputs or Bethe-Salpeter slices. + :param n_symmetries: Number of elements of the auto-discovered symmetry group, 0 without one (see + :func:`rank_input_bytes`). + :param n_point_operations: Number of maps of each of the point group's actions, 0 without them (see + :func:`rank_input_bytes`). :return: A dict mapping each branch key to its :class:`BranchPeak`. """ nb = n_bands @@ -1168,7 +1196,10 @@ def estimate_peaks( giwk_dga_single = scale * sigma_full # the single surviving giwk_dga copy # interpreter, libraries, buffers and the replicated inputs of every rank (rank 0's full-grid interaction joins # the single slots below) - rank_base = overhead * (RANK_BASELINE_BYTES + rank_input_bytes(nk_tot, nk_irr, nb, n_orb)) + rank_base = overhead * ( + RANK_BASELINE_BYTES + + rank_input_bytes(nk_tot, nk_irr, nb, n_orb, n_symmetries, with_eliashberg, n_point_operations) + ) # the MiniPole fallback's modules, which the interpolation may load on every rank for the rest of the run mini_pole = overhead * MINI_POLE_IMPORT_BYTES if niv_interp else 0.0 # the accelerated-mixing history of core-box (iterate, proposal) pairs and the previous proposal's positive core @@ -1196,7 +1227,7 @@ def estimate_peaks( # Single-path FFT bubble (verify-only): multi-rank splits (w, v) columns across ranks (R-space G node-shared); # single-rank builds the whole irr-BZ bubble plus the full-grid multiply buffer per iw (in-place scipy ifftn). # With a shell the columns outside the core box are summed in real space: the bubble holds the core columns with - # the pieces and the sum of the outer ones, and the kernel section the core columns with that sum. + # the sum of the outer ones, and so does the kernel section. gf_window_bubble = 2 * (niv_full + niw_core) summed = niv_full > niv_core v_bubble = bubble_stored_columns(niv_core, niv_full) @@ -1248,6 +1279,8 @@ def estimate_peaks( scale * 4 * core_block + overhead * _chiq_aux_transient(nb * nb * vc, nb), scale * (3 * core_block + KERNEL_GROUP_TRANSIENT * group_block), ) + # beside every stage: the bubble's two frequency sums and the loop's latest physical susceptibility of each channel + chiq_aux_distributed += scale * 4 * _bubble_block(qi, nb, wp, 1) # One node-shared local vertex resident: f_dc_loc is niv_full x niv_core (summed index on the full box), the # surviving one a core-box square. local_vertex_shared = scale * max(_two_fermion_block(1, nb, wp, vf, vc), _two_fermion_block(1, nb, wp, vc)) @@ -1307,9 +1340,9 @@ def column_work(n_tasks: int) -> float: ) if with_eliashberg: - # Slice-direct pairing-vertex build: pp accumulator, two loaded one-fermion inputs (the three-leg vertex stored - # on the pp box for the band) and their momentum-group copies, chunk transient at the driver-sized budget; the - # band's window is the pp box, a streamed one the core. + # Slice-direct pairing-vertex build: pp accumulator, the loaded inputs (the three-leg vertex stored on the pp + # box for the band) and their momentum-group copies, chunk transient at the driver-sized budget; the band's + # window is the pp box, a streamed one the core. one_slice = DTYPE_BYTES * _two_fermion_block(1, nb, 1, vc) fq_nv, fq_nw = (vc, wp) if save_fq else (vpp, vpp) window_slice = DTYPE_BYTES * _two_fermion_block(1, nb, 1, fq_nv) @@ -1326,13 +1359,19 @@ def column_work(n_tasks: int) -> float: ) local_vertex_fq = 0.0 else: + # the inverse bubble, the three-leg vertex and the vertex middle, each with its momentum-group copy fq_distributed = scale * ( _two_fermion_block(qi, nb, 1, vpp) + _bubble_block(qi + q_group, nb, wp, vc) + _bubble_block(qi + q_group, nb, wp, vc if save_fq else vpp) + + _bubble_block(qi + q_group, nb, wp, 1) ) + overhead * _fq_transient(fq_chunk, fq_chunk * vc // fq_nv**2, one_slice, save_fq) # the local vertex the slices are built from, node-shared (counted once per node) local_vertex_fq = scale * _two_fermion_block(1, nb, wp, vc) + # the magnetic vertex is built beside the finished density one, and the singlet and triplet vertices are + # combined from both with one copy (see eliashberg_solver.combine_pairing_vertices) + pp_vertex = scale * _two_fermion_block(qi, nb, 1, vpp) + fq_distributed = max(fq_distributed + pp_vertex, 3 * pp_vertex) peaks["fq"] = BranchPeak( baseline=rank_base + local_vertex_fq + mini_pole, giwk_shareable=local_vertex_fq, @@ -1451,13 +1490,19 @@ def solve_bytes(rows: float) -> float: ) # Start of the non-local routine (verify-only): every rank's fresh-start occupation on its momenta of the DMFT box, - # on a warm start its mu search on its momenta of the niv_cut box instead; on rank 0 with do_spectrum_dmft the - # DMFT lattice Green's function of the whole grid on the DMFT box with its Dyson transient, and on a warm start - # the starting iterate extended onto the DMFT box on the whole grid next to its niv_cut copy and the occupation. + # on a warm start its mu search on its rows of the start on the niv_cut box, then the occupation of those rows + # extended onto the DMFT box; on rank 0 with do_spectrum_dmft the DMFT lattice Green's function of the whole grid + # on the DMFT box with its Dyson transient, and on a warm start the starting iterate extended onto the DMFT box on + # the whole grid next to its niv_cut copy and the occupation. whole_box = _giwk_rspace(nk_tot, nb, dmft_box) occupation_distributed = overhead * _green_function_transients(share_k, n_orb, dmft_box)[1] if warm_start: - occupation_distributed = max(occupation_distributed, mu_update_distributed) + # the cut rows live until their extension is built + cut_rows = scale * _giwk_rspace(share_k, nb, 2 * niv_cut) + extended_rows = scale * _giwk_rspace(share_k, nb, dmft_box) + occupation_distributed = max( + cut_rows + mu_update_distributed, extended_rows + max(cut_rows, occupation_distributed) + ) # with do_spectrum_dmft rank 0 also reloads that Green's function after the loop, cut to the core box, next to # giwk_dga and sigma_dga spectrum_single = max( diff --git a/pyproject.toml b/pyproject.toml index 52332b7f..203ba255 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,6 +48,7 @@ include = ["dgamore*"] [tool.black] line-length = 120 +target-version = ["py312"] [tool.coverage.run] omit = [ diff --git a/tests/test_autodetect_memory.py b/tests/test_autodetect_memory.py index ed74cb86..ac243913 100644 --- a/tests/test_autodetect_memory.py +++ b/tests/test_autodetect_memory.py @@ -37,7 +37,12 @@ def fake_system(monkeypatch): config.box.niv_full = FIXTURE_PARAMS["niv_full"] config.box.niv_dmft = 50 # so niv_cut = min(niw_core + niv_full + 10, niv_dmft) = min(32, 50) = 32 config.eliashberg.perform_eliashberg = False - config.lattice.k_grid = SimpleNamespace(nk_tot=FIXTURE_PARAMS["nk_tot"], nk_irr=FIXTURE_PARAMS["nk_irr"]) + config.lattice.k_grid = SimpleNamespace( + nk_tot=FIXTURE_PARAMS["nk_tot"], + nk_irr=FIXTURE_PARAMS["nk_irr"], + _auto_group=None, + auto_point_group=lambda: None, + ) config.logger = MagicMock() monkeypatch.setattr(dgamore_main.MPI, "Get_processor_name", lambda: "node0", raising=False) @@ -502,7 +507,7 @@ def test_a_node_without_rank_0_holds_only_the_remote_share_of_a_single_rank_peak def test_each_node_sums_its_own_ranks_momentum_counts_and_every_rank_gets_the_same_budgets(fake_system, monkeypatch): """Cyclic nodes sum their ranks' spread counts (1, 2, 1, 2), rank 0's single on its node, on every rank.""" fake_system(1) - config.lattice.k_grid = SimpleNamespace(nk_tot=8, nk_irr=6) + config.lattice.k_grid = SimpleNamespace(nk_tot=8, nk_irr=6, _auto_group=None, auto_point_group=lambda: None) unit, line = 1024.0**3, 6 * 1024.0**3 def counted(**kw): @@ -528,7 +533,7 @@ def counted(**kw): def test_ranks_of_equal_momentum_counts_without_column_tasks_get_an_estimate_of_their_own(fake_system, monkeypatch): """A rank without self-energy column tasks is estimated apart from ranks with tasks and equal momentum counts.""" fake_system(1) - config.lattice.k_grid = SimpleNamespace(nk_tot=16, nk_irr=8) + config.lattice.k_grid = SimpleNamespace(nk_tot=16, nk_irr=8, _auto_group=None, auto_point_group=lambda: None) config.box.niw_core, config.box.niv_core = 0, 1 # one column task, the last rank's ranks = [] diff --git a/tests/test_bubble_gen.py b/tests/test_bubble_gen.py index 53ccfb81..d699129c 100644 --- a/tests/test_bubble_gen.py +++ b/tests/test_bubble_gen.py @@ -456,6 +456,30 @@ def test_bubble_with_a_core_box_transforms_one_column_per_piece_and_no_outer_col assert sum(int(np.prod(shape[3:])) for shape in shapes) == (niw + 1) * (2 * niv_core + len(pieces)) * nb**4 +@pytest.mark.parametrize("serial", [True, False]) +def test_bubble_with_a_core_box_peaks_the_same_however_many_pieces_it_sums(serial, monkeypatch): + """Every transformed piece of outer columns is added to its frequency's sum as it comes, so the peak does not + grow with the number of pieces.""" + nk, nb, niv, niv_core, niw = (32, 32, 1), 2, 40, 2, 2 + config.lattice.nk = nk + rng = np.random.default_rng(4) + shape = (*nk, nb, nb, 2 * (niv + niw + 2)) + mat = rng.standard_normal(shape) + 1j * rng.standard_normal(shape) + q_grid = bz.KGrid(nk, bz.two_dimensional_square_symmetries()) + dist = MpiDistributor.create_distributor(ntasks=q_grid.nk_irr, comm=create_comm_mock()) + build = BubbleGenerator._create_generalized_chi0_q_fft_distributed + if serial: + build = BubbleGenerator.create_generalized_chi0_q_fft + peaks = [] + # 10 pieces per bosonic frequency, then 76: at least as many as the kept columns, so the rounds stay the same + for summed_columns in (8, 1): + monkeypatch.setattr(bubble_gen, "SUMMED_COLUMNS", summed_columns) + g = GreensFunction(mat.copy(), nk=nk) + peaks.append(traced_peak(lambda: build(dist, g, niw, niv, q_grid, 2.5, blocks=True, niv_core=niv_core))[1]) + pieces = np.dtype(n_point_base.DTYPE).itemsize * q_grid.nk_irr * nb**4 * (niw + 1) * (76 - 10) + assert abs(peaks[1] - peaks[0]) < pieces / 10 + + def test_sum_column_products_adds_the_products_of_the_columns_over_both_runs_of_frequencies(): """The stacked product of a block of momenta gives the columns' elementwise products summed over the columns.""" rng, nk, nb, n_v = np.random.default_rng(45), (3, 2, 2), 2, 9 diff --git a/tests/test_eliashberg_solver.py b/tests/test_eliashberg_solver.py index 5a88a744..fe323500 100644 --- a/tests/test_eliashberg_solver.py +++ b/tests/test_eliashberg_solver.py @@ -4013,10 +4013,14 @@ def _write_random_intermediates(no: int, niv: int, niw: int, nq: int): def test_fq_estimate_bounds_the_traced_peak_of_the_pairing_vertex_build( setup, bare_vertex, save_fq, no, niv, niw, budget ): - """The fq model covers the traced peak of the ladder and RPA builds at one-frequency chunks and at whole momenta.""" + """The fq model covers the traced peak of both channels' ladder and RPA builds and of their combination.""" config.eliashberg.save_fq = save_fq - gamma_r, u_loc, v_nonloc = _write_random_intermediates(no, niv, niw, nq=2) - gamma_r = None if bare_vertex else gamma_r + gamma_d, u_loc, v_nonloc = _write_random_intermediates(no, niv, niw, nq=2) + path = config.output.eliashberg_path + for stem in ("vrg_q", "chi_phys_q", "vrg_middle_q"): + np.save(f"{path}/{stem}_magn_rank_0.npy", np.load(f"{path}/{stem}_dens_rank_0.npy")) + gamma_m = LocalFourPoint(gamma_d.mat, SpinChannel.MAGN, 1, 2, False, True) + gammas = (None, None) if bare_vertex else (gamma_d, gamma_m) niv_pp = min(niw // 2, niv // 2) build = ( pairing_vertex.create_pairing_vertex_streaming_fq if save_fq else pairing_vertex.create_pairing_vertex_slice_q_r @@ -4024,7 +4028,9 @@ def test_fq_estimate_bounds_the_traced_peak_of_the_pairing_vertex_build( dist = _make_single_rank_distributor() tracemalloc.start() try: - build(u_loc, v_nonloc, gamma_r, niv_pp, dist, budget, SpinChannel.DENS) + f_dens = build(u_loc, v_nonloc, gammas[0], niv_pp, dist, budget, SpinChannel.DENS) + f_magn = build(u_loc, v_nonloc, gammas[1], niv_pp, dist, budget, SpinChannel.MAGN) + es.combine_pairing_vertices(f_dens, f_magn) peak = tracemalloc.get_traced_memory()[1] finally: tracemalloc.stop() diff --git a/tests/test_local_sde.py b/tests/test_local_sde.py index 31cbe1dc..ada30c77 100644 --- a/tests/test_local_sde.py +++ b/tests/test_local_sde.py @@ -229,6 +229,8 @@ def test_create_full_vertex_from_gamma_matches_dense_padded_solve(o, full_niw, n assert out.niv_first == niv_full and out.niv == niv_core and out.channel == SpinChannel.DENS assert np.allclose(out.mat, ref[..., window], atol=1e-3) assert np.array_equal(gamma_r.mat, gamma_before) + # the bubble's summed shell relies on these rows being bit-identical + assert out.first_frequency_is_constant_outside(niv_core) def test_create_full_vertex_from_gamma_rejects_a_full_box_narrower_than_the_core_box(): diff --git a/tests/test_memory_estimator.py b/tests/test_memory_estimator.py index 1bd286aa..644e38df 100644 --- a/tests/test_memory_estimator.py +++ b/tests/test_memory_estimator.py @@ -2,16 +2,21 @@ # SPDX-License-Identifier: MIT """Unit tests for the pure peak-memory estimator (no MPI, no psutil).""" +import pickle +import tracemalloc import types from dataclasses import replace import numpy as np import pytest +import dgamore.brillouin_zone as brillouin_zone import dgamore.bubble_gen as bubble_gen import dgamore.config as config +import dgamore.eliashberg_solver as eliashberg_solver import dgamore.memory_estimator as memory_estimator import dgamore.sde_kernels as sde_kernels +import dgamore.symmetry_reduction as symmetry_reduction from dgamore.four_point import FourPoint from dgamore.interaction import LocalInteraction from dgamore.jacobian_stabilization import TRACKER_PAIRS @@ -95,7 +100,15 @@ def _peaks(**overrides): def _rank_base(params): """Every rank's share of every baseline: its measured footprint and the inputs it holds a copy of.""" no = params.get("n_orbitals") or params["n_bands"] - inputs = memory_estimator.rank_input_bytes(params["nk_tot"], params["nk_irr"], params["n_bands"], no) + inputs = memory_estimator.rank_input_bytes( + params["nk_tot"], + params["nk_irr"], + params["n_bands"], + no, + params.get("n_symmetries", 0), + params["with_eliashberg"], + params.get("n_point_operations", 0), + ) return RANK_BASELINE_BYTES + inputs @@ -156,7 +169,8 @@ def test_every_branch_has_positive_baseline_and_off_transient(): shared = ("chi0q", "chiq_aux", "sde", "chi0q_core", "fq", "sigma_loop", "mu_update", "energies") for key, bp in peaks.items(): assert isinstance(bp, BranchPeak) - base = _rank_base(BASE) # every rank's footprint sits in every baseline, the interaction in rank 0's slots + # every rank's footprint sits in every baseline, the interaction in rank 0's slots + base = _rank_base({**BASE, "with_eliashberg": True}) assert bp.baseline > base if key in shared else bp.baseline == base assert bp.off_distributed + bp.off_single > 0 @@ -169,6 +183,59 @@ def test_every_baseline_counts_the_inputs_every_rank_holds_a_copy_of(): assert all(bp.baseline >= RANK_BASELINE_BYTES + inputs for bp in _peaks(with_eliashberg=True).values()) +def test_every_baseline_counts_the_symmetry_maps_and_the_eliashberg_stars_of_the_inputs(): + """Every baseline holds the inputs of an auto grid with its point group and the Eliashberg stars.""" + params = {**BASE, "with_eliashberg": True, "n_symmetries": 8, "n_point_operations": 8} + assert all(bp.baseline >= _rank_base(params) for bp in estimate_peaks(**params).values()) + + +def _cubic_hk(n_orbitals: int, n: int) -> np.ndarray: + """A cubic dispersion of one s band or three t2g bands with real interorbital hopping, on an n^3 grid.""" + k = np.meshgrid(*[2 * np.pi * np.arange(n) / n] * 3, indexing="ij") + c, s = np.cos(k), np.sin(k) + if n_orbitals == 1: + return (-2.0 * c.sum(axis=0))[..., None, None].astype(complex) + hk = np.zeros((n,) * 3 + (3, 3), dtype=complex) + # the orbital of the plane (a, b) hops in it and weakly along the third axis, and couples the other two orbitals + for orbital, (a, b, z) in enumerate(((0, 1, 2), (0, 2, 1), (1, 2, 0))): + hk[..., orbital, orbital] = -2.0 * (c[a] + c[b]) - 0.4 * c[z] + p, q = [o for o in range(3) if o != orbital] + hk[..., p, q] = hk[..., q, p] = -0.1 * s[a] * s[b] + return hk + + +@pytest.mark.parametrize("with_eliashberg", [False, True]) +@pytest.mark.parametrize("n_orbitals", [1, 3]) +def test_the_symmetry_inputs_match_what_a_rank_holds_of_a_broadcast_auto_grid(n_orbitals, with_eliashberg): + """A rank's group keys, point-group maps, grid-action cache and stars of a broadcast grid are its estimate.""" + grid = brillouin_zone.KGrid(nk=(12, 12, 12), symmetries=[brillouin_zone.KnownSymmetries.AUTO]) + grid.specify_auto_symmetries(_cubic_hk(n_orbitals, 12)) + # a rank other than 0 unpickles the broadcast grid beside empty module caches + received = pickle.loads(pickle.dumps(grid)) + symmetry_reduction._clear_grid_action_cache() + eliashberg_solver._wedge_orbits.cache_clear() + tracemalloc.start() + try: + entry = tracemalloc.get_traced_memory()[0] + point_group = received.auto_point_group() + received.auto_point_group(real_space=True) + if with_eliashberg: + eliashberg_solver.wedge_window_points(received) + eliashberg_solver.block_size(received) + held = tracemalloc.get_traced_memory()[0] - entry + tracer = tracemalloc.take_snapshot().filter_traces([tracemalloc.Filter(True, "*/coverage/*")]) + finally: + tracemalloc.stop() + held -= sum(trace.size for trace in tracer.traces) + keys = sum(len(element._key[0]) for element in received._auto_group) + n_operations = 0 if point_group is None else len(point_group[0]) + assert (n_orbitals == 1) == (n_operations == 0) + nk, inputs = grid.nk_tot, memory_estimator.rank_input_bytes + plain = inputs(nk, grid.nk_irr, n_orbitals, n_orbitals) + expected = inputs(nk, grid.nk_irr, n_orbitals, n_orbitals, len(received._auto_group), with_eliashberg, n_operations) + assert keys + held == pytest.approx(expected - plain, rel=0.05) + + def test_uncorrelated_orbitals_add_only_the_dispersion_to_the_inputs_every_rank_holds(): """occ_k and the symmetry rotations hold the correlated orbitals, so uncorrelated ones grow only e(k).""" nk, inputs = 70**3, memory_estimator.rank_input_bytes @@ -279,7 +346,9 @@ def test_giwk_shareable_is_every_array_of_each_sde_section_baseline(): """The loop Sigma is node-shared like the Green's functions, so only the per-rank footprint stays unshared.""" peaks = _peaks(with_eliashberg=True) for key in ("chi0q", "chiq_aux", "sde"): - assert peaks[key].giwk_shareable == pytest.approx(peaks[key].baseline - _rank_base(BASE)) + assert peaks[key].giwk_shareable == pytest.approx( + peaks[key].baseline - _rank_base({**BASE, "with_eliashberg": True}) + ) def test_mixing_history_sits_in_the_rows_of_every_rank_in_every_proposal_branch(): @@ -311,7 +380,7 @@ def test_interpolation_reserves_the_mini_pole_modules_after_the_loop(spectrum): plain, interpolating = _peaks(**params), _peaks(**params, niv_interp=40) after_loop = {"chi0q_core", "fq", "lanczos"} | ({"occupation"} if spectrum else set()) assert after_loop <= plain.keys() and interpolating.keys() - plain.keys() == {"sigma_interp"} - assert interpolating["sigma_interp"].baseline == _rank_base(BASE) + MINI_POLE_IMPORT_BYTES + assert interpolating["sigma_interp"].baseline == _rank_base({**BASE, **params}) + MINI_POLE_IMPORT_BYTES for key, bp in plain.items(): added = MINI_POLE_IMPORT_BYTES if key in after_loop else 0 assert interpolating[key] == replace(bp, baseline=bp.baseline + added), key @@ -324,7 +393,7 @@ def test_eliashberg_branches_share_only_the_local_vertex_of_the_pairing_vertex_b local_vertex = SCALE * BASE["n_bands"] ** 4 * (BASE["niw_core"] + 1) * (2 * BASE["niv_core"]) ** 2 for key, shared in (("fq", local_vertex), ("lanczos", 0.0)): assert peaks[key].giwk_shareable == pytest.approx(shared) - assert peaks[key].baseline == pytest.approx(_rank_base(BASE) + shared) + assert peaks[key].baseline == pytest.approx(_rank_base({**BASE, "with_eliashberg": True}) + shared) assert peaks[key].off_single >= giwk_dga assert peaks[key].on_single >= giwk_dga @@ -346,22 +415,25 @@ def _chiq_aux_transient(): def _fq_branch(budget, streaming=False): - """The TINY fq branch: accumulator, loaded and group-copied bubbles, 3 windows + 6 one-fermion + 4 (9) slices.""" + """The TINY fq branch: the magnetic build beside the density vertex, or the combination's three vertices.""" nb, wp, vc, vpp = TINY["n_bands"], TINY["niw_core"] + 1, 2 * TINY["niv_core"], 2 * TINY["niv_pp"] qi = -(-TINY["nk_irr"] // TINY["n_ranks"]) nv, nw = (vc, wp) if streaming else (vpp, vpp) window_slice = DTYPE_BYTES * nb**4 * nv * nv chunk = min(max(budget, window_slice), qi * nw * window_slice) group = max(1, chunk // (nw * window_slice)) - # the inverse bubble on the core box, the three-leg vertex on the pp box unless the full vertex is streamed - residents = SCALE * (qi * nb**4 * vpp * vpp + (qi + group) * nb**4 * wp * (vc + (vc if streaming else vpp))) + # the inverse bubble on the core box, the three-leg vertex on the pp box unless the full vertex is streamed, the + # vertex middle + pp_vertex = SCALE * qi * nb**4 * vpp * vpp + residents = 2 * pp_vertex + SCALE * (qi + group) * nb**4 * wp * (vc + (vc if streaming else vpp) + 1) slices = (9 if streaming else 4) * DTYPE_BYTES * nb**4 * vc * vc - return residents + OVERHEAD_FACTOR * (3 * chunk + 6 * (chunk * vc // nv**2) + slices), window_slice, qi * nw + build = residents + OVERHEAD_FACTOR * (3 * chunk + 6 * (chunk * vc // nv**2) + slices) + return max(build, 3 * pp_vertex), window_slice, qi * nw @pytest.mark.parametrize("n_ranks", [1, 4]) def test_chiq_aux_block_is_the_largest_kernel_section_stage(n_ranks): - """The chiq_aux transient is the largest of the box parts, the attachment, the aux-sum solve and the groups.""" + """The chiq_aux transient, with the bubble sums and the latest susceptibilities, is the largest kernel stage.""" params = {**TINY, "n_ranks": n_ranks, "niv_full": 40, "nk_irr": 2000, "nk_tot": 8000} nb, wp, vc = TINY["n_bands"], TINY["niw_core"] + 1, 2 * TINY["niv_core"] qi = -(-params["nk_irr"] // n_ranks) @@ -369,11 +441,14 @@ def test_chiq_aux_block_is_the_largest_kernel_section_stage(n_ranks): # several ranks consume the bubble one bosonic frequency at a time, one rank holds it whole parts = 2 * core if n_ranks == 1 else 2 * qi * nb**4 * vc for niv_full, held in ((40, vc + 1), (TINY["niv_core"], vc)): # the core box with its outer sum, the full box - expected = max( - SCALE * (qi * nb**4 * wp * held + parts), - SCALE * 4 * core, - SCALE * 4 * core + OVERHEAD_FACTOR * _chiq_aux_transient(), - SCALE * (3 * core + KERNEL_GROUP_TRANSIENT * group), + expected = ( + max( + SCALE * (qi * nb**4 * wp * held + parts), + SCALE * 4 * core, + SCALE * 4 * core + OVERHEAD_FACTOR * _chiq_aux_transient(), + SCALE * (3 * core + KERNEL_GROUP_TRANSIENT * group), + ) + + SCALE * 4 * qi * nb**4 * wp ) bp = estimate_peaks(**{**params, "niv_full": niv_full})["chiq_aux"] assert bp.off_distributed == pytest.approx(expected) and bp.on_distributed == bp.off_distributed @@ -424,7 +499,7 @@ def test_chi0q_fast_single_counts_buffer_ifftn_transient_and_g_copies(): nb, wp, vc = TINY["n_bands"], TINY["niw_core"] + 1, 2 * TINY["niv_core"] for niv_full in (TINY["niv_full"], TINY["niv_core"]): # a shell, whose columns are summed, and none params, vf = {**TINY, "n_ranks": 1, "niv_full": niv_full}, 2 * niv_full - stored, buffered = (vc + 2, vc + 1) if niv_full > TINY["niv_core"] else (vf, vf) + stored = buffered = vc + 1 if niv_full > TINY["niv_core"] else vf bubble_irr = TINY["nk_irr"] * nb**4 * wp * stored fft_buffers = (1 + CHI0Q_IFFTN_TRANSIENT_FACTOR) * TINY["nk_tot"] * nb**4 * buffered gf_copies = 2 * TINY["nk_tot"] * nb**2 * (2 * (niv_full + TINY["niw_core"])) @@ -439,20 +514,18 @@ def test_chi0q_distributed_is_the_result_slice_and_the_column_work_of_the_rank() qi = -(-TINY["nk_irr"] // TINY["n_ranks"]) for niv_full in (TINY["niv_full"], TINY["niv_core"]): # a shell, whose columns are summed, and none summed = niv_full > TINY["niv_core"] - stored = vc + 2 if summed else 2 * niv_full + stored = vc + 1 if summed else 2 * niv_full n_cols = -(-wp * stored // TINY["n_ranks"]) column = memory_estimator.bubble_column_bytes(TINY["nk_tot"], TINY["nk_irr"], nb, n_cols, qi, summed) peak = estimate_peaks(**{**TINY, "niv_full": niv_full})["chi0q"].off_distributed assert peak == pytest.approx(SCALE * qi * nb**4 * wp * stored + column) -def test_bubble_stored_columns_are_the_core_columns_with_the_pieces_and_the_sum_of_the_outer_ones(): - """With a shell the bubble holds its core columns, one column per piece of outer columns and their sum.""" - assert memory_estimator.BUBBLE_SUMMED_COLUMNS == bubble_gen.SUMMED_COLUMNS +def test_bubble_stored_columns_are_the_core_columns_and_the_sum_of_the_outer_ones(): + """With a shell the bubble holds its core columns and the sum of the outer ones, no piece of them.""" assert memory_estimator.bubble_stored_columns(40, 40) == 80 for niv_core, niv_full in ((40, 140), (5, 6), (2, 18)): - pieces = len(bubble_gen.BubbleGenerator._summed_pieces(niv_full, niv_core)) - assert memory_estimator.bubble_stored_columns(niv_core, niv_full) == 2 * niv_core + pieces + 1 + assert memory_estimator.bubble_stored_columns(niv_core, niv_full) == 2 * niv_core + 1 work = [memory_estimator.bubble_column_bytes(1000, 100, 2, 3, 4, summed) for summed in (False, True)] assert work[1] - work[0] == DTYPE_BYTES * 1000 * 2**4 + 3 * 2**20 @@ -697,15 +770,20 @@ def test_occupation_branch_adds_the_dmft_lattice_green_function_on_rank0_only_wi def test_occupation_branch_holds_the_warm_start_on_rank0_and_its_mu_search_on_every_rank(): """On a warm start rank 0 extends the whole-grid starting iterate onto the DMFT box next to its niv_cut copy and - the occupation chunks, and every rank searches mu on its momenta.""" + the occupation chunks, and every rank searches mu on its rows of the start, then extends them onto the DMFT box.""" nb, nk, box = TINY["n_bands"], TINY["nk_tot"], 2 * TINY["niv_dmft"] peaks = estimate_peaks(**TINY, warm_start=True) warm = peaks["occupation"] occupation = memory_estimator._green_function_transients(nk, nb, box)[1] sigma_full = nk * nb**2 * 2 * TINY["niv_cut"] assert warm.off_single == pytest.approx(SCALE * (nk * nb**2 * box + sigma_full) + occupation + _v_single(TINY)) - assert warm.off_distributed >= peaks["mu_update"].off_distributed assert estimate_peaks(**TINY)["occupation"].off_single == _v_single(TINY) + # every rank's rows of the start on the niv_cut box, then extended onto the DMFT box + share_k = -(-nk // TINY["n_ranks"]) + cut, extended = SCALE * share_k * nb**2 * 2 * TINY["niv_cut"], SCALE * share_k * nb**2 * box + sums = OVERHEAD_FACTOR * memory_estimator._green_function_transients(share_k, nb, box)[1] + mu_search = cut + peaks["mu_update"].off_distributed + assert warm.off_distributed == pytest.approx(max(mu_search, extended + max(cut, sums))) def test_sigma_loop_holds_the_iterate_windows_per_node_and_the_mixing_of_every_ranks_rows():