# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Estimate a run's memory before launching it.
The unit is the **field volume**, ``F = 16 n_y n_x n_omega`` bytes: one complex128
copy of the propagated state (5.27 GiB at the 768 x 768 x 600 production shape).
A run holds:
- solprop's backend, buffer by buffer, from its own ledger
(:meth:`solprop.backends.protocol.Backend.memory_ledger`);
- the translated problem's copy of the placeholder input, a single broadcast row;
- the formed input of each delay point, one F while solprop copies it in;
- with the host reduction, solprop's copy of each saved plane, one F per plane while
it is reduced;
- the host reducer's per-row partial sums and this package's setup tables, small.
The planes and the formed input are never alive together, so the peak is the
persistent part plus one F.
solprop has no estimate that does not build the backend (its ADR-065: memory is
bounded by the scheduler, not checked in advance), so forming this one builds the
backend, reads its ledger and closes it. Run it where the job will run: a
configuration that does not fit fails here as the run would.
"""
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, fields
import numpy as np
from jaxtyping import Float
from pnps.bridge import ReductionChoice, _translate
from pnps.pulse import energy_prefactor
from pnps.reduce_numba import Reducer
from pnps.setup import Setup
__all__ = ["MemoryBudget", "memory_budget"]
[docs]
@dataclass(frozen=True)
class MemoryBudget:
"""A run's memory, by part, in bytes.
Attributes
----------
backend : str
The solprop backend the estimate is for (``"auto"`` resolved).
field_volume : int
One complex128 copy of the state, ``16 n_y n_x n_omega`` bytes.
engine : collections.abc.Mapping
solprop's persistent bytes by buffer (the backend's ``memory_ledger()``).
problem_input : int
The translated problem's copy of the placeholder input.
formed_input : int
One delay point's formed input, transient.
plane_copy : int
solprop's host copy of a saved plane with the host reduction, transient; 0
when solprop's statistics reduce the planes.
reducer : int
The host reducer's buffers.
setup : int
This package's setup tables (the input former, the spectra, the absorber).
exact_masks : int
With ``Config.exact_windows``, the windows' exact hard-disc masks, held for
the life of the bridge; 0 otherwise.
exact_input : int
With ``Config.exact_windows``, the input state the run holds for the
subtraction of the linear part, a field volume; 0 otherwise.
exact_plane : int
With ``Config.exact_windows``, each plane's transient linear part and
nonlinear part, two field volumes; 0 otherwise.
"""
backend: str
field_volume: int
engine: Mapping[str, int]
problem_input: int
formed_input: int
plane_copy: int
reducer: int
setup: int
exact_masks: int = 0
exact_input: int = 0
exact_plane: int = 0
[docs]
@property
def engine_total(self) -> int:
"""Return solprop's persistent bytes.
Returns
-------
int
The sum of :attr:`engine`.
"""
return sum(self.engine.values())
[docs]
@property
def persistent(self) -> int:
"""Return the bytes held for the life of a bridge.
Returns
-------
int
The engine, the problem's input copy, the reducer, the setup and the
exact windows' masks.
"""
return (
self.engine_total
+ self.problem_input
+ self.reducer
+ self.setup
+ self.exact_masks
)
[docs]
@property
def peak(self) -> int:
"""Return the largest number of bytes held at once.
Returns
-------
int
:attr:`persistent` plus the input the exact windows hold, plus the
larger transient: the formed input, or a plane's host copy with the
exact windows' parts of it (they are never alive together).
"""
return (
self.persistent
+ self.exact_input
+ max(self.formed_input, self.plane_copy + self.exact_plane)
)
[docs]
@property
def volumes(self) -> float:
"""Return the peak in field volumes.
Returns
-------
float
:attr:`peak` divided by :attr:`field_volume`.
"""
return self.peak / self.field_volume
[docs]
def report(self) -> str:
"""Return the budget as a short table, GiB and field volumes.
Returns
-------
str
One line per part and the peak.
"""
gib = 2.0**30
rows = [
(f"engine ({self.backend})", self.engine_total),
("problem input copy", self.problem_input),
("formed input (transient)", self.formed_input),
("plane copy (transient)", self.plane_copy),
("host reducer", self.reducer),
("setup tables", self.setup),
]
if self.exact_masks:
rows += [
("exact window masks", self.exact_masks),
("held input (exact)", self.exact_input),
("exact plane parts (trans.)", self.exact_plane),
]
rows.append(("peak", self.peak))
lines = [
f"{name:26s} {size / gib:9.3f} GiB {size / self.field_volume:7.2f} F"
for name, size in rows
]
return "\n".join(lines)
[docs]
def memory_budget(
setup: Setup,
zsave: Float[np.ndarray, "*shape"] | Sequence[float],
h_target: float,
*,
backend: str = "auto",
node_budget: int | None = None,
reduction: ReductionChoice | None = None,
) -> MemoryBudget:
"""Estimate the memory of a run before launching it.
Takes the arguments of :func:`pnps.bridge.build_bridge` that decide memory,
translates the configuration as it does, and builds the backend for its ledger,
closing it again before returning.
Parameters
----------
setup : Setup
The configuration (:func:`pnps.setup.build_setup`).
zsave : array_like
Save positions in m.
h_target : float
Largest step of the replayed schedule, m.
backend : str, optional
The solprop backend registry name; ``"auto"`` resolves as solprop resolves it.
node_budget : int or None, optional
The per-chunk memory budget of solprop in bytes; None takes the configuration's.
reduction : {"auto", "host", "solprop"} or None, optional
Where planes are reduced; None takes the configuration's.
Returns
-------
MemoryBudget
The parts, their peak and its size in field volumes.
"""
t = _translate(
setup,
zsave,
h_target,
backend=backend,
node_budget=node_budget,
nonlinear=True,
pin_frame=True,
reduction=reduction,
)
# The bridge's own construction (its runner), so the backend carries the same run
# request and node budget.
runner = t.simulation.runner()
try:
name, ledger = runner.backend.name, dict(runner.backend.memory_ledger())
finally:
runner.close()
tgrid, sgrid = setup.tgrid, setup.sgrid
volume = 16 * sgrid.n * sgrid.n * tgrid.nt
reducer = Reducer(
t.tables,
sgrid.kx,
setup.windows,
energy_prefactor(tgrid, sgrid),
setup.cfg.edge_diagnostic,
setup.signal_region,
)
host_planes = t.reduction == "host" or setup.cfg.edge_diagnostic
# On the host the exact windows hold their masks, the input and each plane's
# linear part; through solprop they are the backend's, inside its ledger.
exact = setup.cfg.exact_windows and t.reduction == "host"
omega = tgrid.omega
band = int(np.count_nonzero((omega > 0.0) & (np.real(t.tables.k2) > 0.0)))
return MemoryBudget(
backend=name,
field_volume=volume,
engine=ledger,
problem_input=_held_bytes(t.problem.initial.field0),
formed_input=volume,
plane_copy=volume if host_planes else 0,
reducer=_array_bytes(reducer),
setup=_array_bytes(setup) + _array_bytes(setup.former),
exact_masks=8 * band * len(setup.windows) * sgrid.n**2 if exact else 0,
exact_input=volume if exact else 0,
exact_plane=2 * volume if exact else 0,
)
def _held_bytes(array: np.ndarray) -> int:
"""Return the bytes an array's memory holds, a broadcast counted once.
Parameters
----------
array : numpy.ndarray
Any array, possibly a broadcast view with zero strides.
Returns
-------
int
The item size times the extent of every axis with a non-zero stride.
"""
held = [n for n, step in zip(array.shape, array.strides, strict=True) if step != 0]
return int(array.itemsize * np.prod(held, dtype=np.int64))
def _array_bytes(record: object) -> int:
"""Return the bytes of the arrays an object holds as attributes.
Parameters
----------
record : object
A dataclass or an object with a ``__dict__``.
Returns
-------
int
The sum of ``nbytes`` over its array attributes.
"""
if hasattr(record, "__dataclass_fields__"):
values = [getattr(record, f.name) for f in fields(record)] # type: ignore[arg-type]
else:
values = list(vars(record).values())
return sum(int(v.nbytes) for v in values if isinstance(v, np.ndarray))