###############################################################################
# mpi-sppy: MPI-based Stochastic Programming in PYthon
#
# Copyright (c) 2024, Lawrence Livermore National Security, LLC, Alliance for
# Sustainable Energy, LLC, The Regents of the University of California, et al.
# All rights reserved. Please see the files COPYRIGHT.md and LICENSE.md for
# full copyright and license information.
###############################################################################
import logging
import math
import os
import time
import warnings
import numpy as np
import pyomo.environ as pyo
import mpisppy.MPI as MPI
import mpisppy.spopt
import mpisppy.utils.checkpointing as checkpointing
import mpisppy.utils.sputils as sputils
from mpisppy import global_toc
from mpisppy.utils.linear_surrogate import set_derived_surrogate_rhos
from mpisppy.utils.prox_approx import ProxApproxManager
from mpisppy.utils.rho_utils import check_rhos_positive
# decorator snarfed from stack overflow - allows per-rank profile output file generation.
[docs]
def profile(filename=None, comm=MPI.COMM_WORLD):
pass
logger = logging.getLogger('PHBase')
logger.setLevel(logging.WARN)
# Shared remediation hint for the quadratic-prox / solver compatibility checks
# (issue #762): a solver that cannot handle the quadratic proximal term should
# linearize it instead.
_LINEARIZE_PROX_HINT = (
"Re-run with --linearize-proximal-terms (add "
"--linearize-binary-proximal-terms for binary variables)."
)
#======================
def _Compute_Xbar(opt, verbose=False):
""" Gather xbar and x squared bar for each node in the list and
distribute the values back to the scenarios.
Args:
opt (phbase or xhat_eval object): object with the local scenarios
verbose (boolean):
If True, prints verbose output.
"""
"""
Note:
Each scenario knows its own probability and its nodes.
Note:
The scenario only "sends a reduce" to its own node's comms so even
though the rank is a member of many comms, the scenario won't
contribute to the wrong node.
Note:
As of March 2019, we concatenate xbar and xsqbar into one long
vector to make it easier to use the current asynch code.
"""
nodenames = [] # to transmit to comms
local_concats = {} # keys are tree node names
global_concats = {} # values are concat of xbar and xsqbar
# we need to accumulate all local contributions before the reduce
for k,s in opt.local_scenarios.items():
nlens = s._mpisppy_data.nlens
for node in s._mpisppy_node_list:
if node.name not in nodenames:
ndn = node.name
nodenames.append(ndn)
mylen = 2*nlens[ndn]
local_concats[ndn] = np.zeros(mylen, dtype='d')
global_concats[ndn] = np.zeros(mylen, dtype='d')
# compute the local xbar and sqbar (put the sq in the 2nd 1/2 of concat)
for k,s in opt.local_scenarios.items():
nlens = s._mpisppy_data.nlens
for node in s._mpisppy_node_list:
ndn = node.name
nlen = nlens[ndn]
xbars = local_concats[ndn][:nlen]
xsqbars = local_concats[ndn][nlen:]
nonants_array = np.fromiter((v._value for v in node.nonant_vardata_list),
dtype='d', count=nlen)
probs = s._mpisppy_data.prob_coeff[ndn] * np.ones(nlen)
xbars += probs * nonants_array
xsqbars += probs * nonants_array**2
# compute node xbar values(reduction)
for nodename in nodenames:
opt.comms[nodename].Allreduce(
[local_concats[nodename], MPI.DOUBLE],
[global_concats[nodename], MPI.DOUBLE],
op=MPI.SUM)
# set the xbar and xsqbar in all the scenarios
for k,s in opt.local_scenarios.items():
logger.debug(f' top of assign xbar loop for {k} on rank {opt.cylinder_rank}')
nlens = s._mpisppy_data.nlens
for node in s._mpisppy_node_list:
ndn = node.name
nlen = nlens[ndn]
xbars = global_concats[ndn][:nlen]
xsqbars = global_concats[ndn][nlen:]
for i in range(nlen):
s._mpisppy_model.xbars[(ndn,i)]._value = xbars[i]
s._mpisppy_model.xsqbars[(ndn,i)]._value = xsqbars[i]
if verbose: # and opt.cylinder_rank == 0:
print ("cylinder rank, scen, node, var, xbar:",
opt.cylinder_rank, k, ndn, node.nonant_vardata_list[i].name,
pyo.value(s._mpisppy_model.xbars[(ndn,i)]))
[docs]
def Wbar_by_node(opt):
"""E[W] per tree node: the probability-weighted sum of W over scenarios.
sum_s p_s W_s = 0 is the dual feasibility a Lagrangian bound built from W
relies on, and is what makes W a point in the orthogonal complement of the
nonanticipativity subspace. PH's Update_W keeps it when rho is the same in
every scenario: it adds rho * (x_s - xbar), and xbar is the probability
weighted mean, so the additions sum to zero when rho factors out. Then
every entry of what comes back is zero up to the drift of accumulating it
in floating point, which is a fraction of the size of the weights
themselves (see W_magnitude_by_node).
It is not guaranteed. The rho setter is called once per scenario and may
return a different rho for each, and then E[W] moves away from zero.
``project_W_to_zero_sum`` repairs every local scenario copy and is used by
W-receiving outer-bound spokes for mixed-generation APH snapshots. The
older diagnostic ``_Compute_Wbar`` is called by APH when
display_convergence_detail is set; it subtracts only on cylinder rank 0's
scenarios, so on more than one rank it does not bring E[W] to zero.
Collective: the scenarios of a node are spread over the ranks, so the sum
is an Allreduce over that node's comm and every rank gets the same
answer. Returns {node name: numpy array over the node's nonants}.
Args:
opt (phbase or xhat_eval object): object with the local scenarios
"""
return _prob_weighted_W_by_node(opt, magnitude=False)
[docs]
def W_magnitude_by_node(opt):
"""E[|W|] per tree node: how big the numbers behind E[W] are.
The companion to Wbar_by_node, for judging one of its entries. Whether a
given E[W] is "zero" is a question about the size of the terms that were
summed to get it: a sum of 1e-6 is float dust beside weights of 1e6 and a
real violation beside weights of 1e-3. Same collective shape.
Args:
opt (phbase or xhat_eval object): object with the local scenarios
"""
return _prob_weighted_W_by_node(opt, magnitude=True)
[docs]
def project_W_to_zero_sum(opt):
"""Project scenario weights onto the dual-feasible nonanticipativity space.
For every scenario-tree node and nonanticipative position, subtract the
probability-weighted node mean from every active local scenario copy.
Variable-probability copies with zero probability remain masked to zero.
This is a collective operation over the node communicators. It is useful
when an asynchronous publisher supplies pieces of W from different
generations: the mixed snapshot is not necessarily dual feasible, but its
projection is and can therefore be used for a valid Lagrangian bound.
Returns the node-wise means that were removed.
"""
Wbars_by_node = Wbar_by_node(opt)
for scenario in opt.local_scenarios.values():
data = scenario._mpisppy_data
for (ndn, i) in scenario._mpisppy_data.nonant_indices:
node_mask = getattr(data, "prob0_mask", {}).get(ndn, 1.0)
mask = node_mask[i] if isinstance(node_mask, np.ndarray) \
else node_mask
scenario._mpisppy_model.W[(ndn, i)]._value -= \
mask * Wbars_by_node[ndn][i]
return Wbars_by_node
def _prob_weighted_W_by_node(opt, magnitude):
"""Sum_s p_s W_s per node, or sum_s p_s |W_s| when magnitude is True."""
nodenames = [] # to transmit to comms
local_concats = {} # keys are tree node names
global_concats = {} # values are concat of xbar and xsqbar
# we need to accumulate all local contributions before the reduce
for k,s in opt.local_scenarios.items():
nlens = s._mpisppy_data.nlens
for node in s._mpisppy_node_list:
if node.name not in nodenames:
ndn = node.name
nodenames.append(ndn)
mylen = nlens[ndn]
local_concats[ndn] = np.zeros(mylen, dtype='d')
global_concats[ndn] = np.zeros(mylen, dtype='d')
# compute the local Wbar
for k,s in opt.local_scenarios.items():
nlens = s._mpisppy_data.nlens
for node in s._mpisppy_node_list:
ndn = node.name
nlen = nlens[ndn]
Wbars = local_concats[ndn][:nlen]
# s._mpisppy_data.nonant_indices.keys() indexes the W Param
Wnonants_array = np.fromiter((pyo.value(s._mpisppy_model.W[idx]) for idx in s._mpisppy_data.nonant_indices if idx[0] == ndn),
dtype='d', count=nlen)
probs = s._mpisppy_data.prob_coeff[ndn] * np.ones(nlen)
if magnitude:
Wnonants_array = np.abs(Wnonants_array)
Wbars += probs * Wnonants_array
# compute node xbar values(reduction)
for nodename in nodenames:
opt.comms[nodename].Allreduce(
[local_concats[nodename], MPI.DOUBLE],
[global_concats[nodename], MPI.DOUBLE],
op=MPI.SUM)
return global_concats
def _Compute_Wbar(opt, verbose=False, repair=True):
""" Seldom used (mainly for diagnostics); gather Wbar for each node.
Args:
opt (phbase or xhat_eval object): object with the local scenarios
verbose (boolean):
If True, prints verbose output.
repair (boolean):
If True, normalize the W values so EW = 0
"""
global_concats = Wbar_by_node(opt)
# check the Wbar
for k,s in opt.local_scenarios.items():
logger.debug(f' top of Wbar loop for {k} on rank {opt.cylinder_rank}')
nlens = s._mpisppy_data.nlens
for node in s._mpisppy_node_list:
ndn = node.name
nlen = nlens[ndn]
Wbars = global_concats[ndn][:nlen]
for i in range(nlen):
if abs(Wbars[i]) > opt.E1_tolerance and opt.cylinder_rank == 0:
print(f"EW={Wbars[i]} (should be zero) for {node.nonant_vardata_list[i].name}")
if repair:
print(f" repairing in {k}")
s._mpisppy_model.W[(ndn,i)]._value -= Wbars[i]
#======================
[docs]
class PHBase(mpisppy.spopt.SPOpt):
""" Base class for all PH-based algorithms.
Based on mpi4py (but should run with, or without, mpi)
EVERY INDEX IS ZERO-BASED! (Except stages, which are one based).
Node names other than ROOT, although strings, must be a number or end
in a number because mpi4py comms need a number. PH using a smart
referencemodel that knows how to make its own tree nodes and just wants
a trailing number in the scenario name. Assume we have only non-leaf
nodes.
To check for rank 0 use self.cylinder_rank == 0.
Attributes:
local_scenarios (dict):
Dictionary mapping scenario names (strings) to scenarios (Pyomo
conrete model objects). These are only the scenarios managed by
the current rank (not all scenarios in the entire model).
comms (dict):
Dictionary mapping node names (strings) to MPI communicator
objects.
local_scenario_names (list):
List of local scenario names (strings). Should match the keys
of the local_scenarios dict.
current_solver_options (dict): from options, but callbacks might
Dictionary of solver options provided in options. Note that
callbacks could change these options.
Args:
options (dict):
Options for the PH algorithm.
all_scenario_names (list):
List of all scenario names in the model (strings).
scenario_creator (callable):
Function which take a scenario name (string) and returns a
Pyomo Concrete model with some things attached.
scenario_denouement (callable, optional):
Function which does post-processing and reporting.
all_nodenames (list, optional):
List of all node name (strings). Can be `None` for two-stage
problems.
mpicomm (MPI comm, optional):
MPI communicator to use between all scenarios. Default is
`MPI.COMM_WORLD`.
scenario_creator_kwargs (dict, optional):
Keyword arguments passed to `scenario_creator`.
extensions (object, optional):
PH extension object.
extension_kwargs (dict, optional):
Keyword arguments to pass to the extensions.
ph_converger (object, optional):
PH converger object.
rho_setter (callable, optional):
Function to set rho values throughout the PH algorithm.
variable_probability (callable, optional):
Function to set variable specific probabilities.
"""
# Resume state, set by _restore_from_checkpoint_if_resuming when
# --resume-from is given. Class-level defaults so every other code path
# -- including runs with no checkpointing at all -- reads sane values.
_resumed_from_checkpoint = False
_resume_iteration = 0
_checkpoint_leaf_state = None
#: Wall-clock seconds of the most recent full PH iteration, as of the
#: checkpoint hook: --checkpoint-before-seconds has to ask there whether
#: there is time for another iteration. Measured between consecutive
#: passes through the same point in iterk_loop (see there). None until
#: the first iteration's solve is done.
_last_iteration_seconds = None
#: Absolute number of the last iteration this run may perform, set by
#: iterk_loop from --max-iterations (which bounds the run) and
#: --stop-at-iteration-number (which bounds the study). Kept on the object
#: because the Checkpointer has to recognize the final iteration to write
#: it whatever the checkpoint cadence says.
_stop_iteration = None
def __init__(
self,
options,
all_scenario_names,
scenario_creator,
scenario_denouement=None,
all_nodenames=None,
mpicomm=None,
scenario_creator_kwargs=None,
extensions=None,
extension_kwargs=None,
ph_converger=None,
rho_setter=None,
variable_probability=None,
):
self._PHIter = 0 # moved to _init June 2024 so extensions can see it
""" PHBase constructor. """
self._configure_slurm_deadline(options)
super().__init__(
options,
all_scenario_names,
scenario_creator,
scenario_denouement=scenario_denouement,
all_nodenames=all_nodenames,
mpicomm=mpicomm,
extensions=extensions,
extension_kwargs=extension_kwargs,
scenario_creator_kwargs=scenario_creator_kwargs,
variable_probability=variable_probability,
)
global_toc("Initializing PHBase")
if self._slurm_deadline is not None:
global_toc(
self._slurm_limit_message(),
self.cylinder_rank == 0,
)
# Note that options can be manipulated from outside on-the-fly.
# self.options (from super) will archive the original options.
self.options = options
self.Ag = options.get("Ag", None) # The Agnostic Object
self.options_check()
self.ph_converger = ph_converger
self.rho_setter = rho_setter
# solver_options_layers, _dynamic_solver_options_layer,
# current_solver_options, and _effective_solver_options are
# set up in SPOpt.__init__; PHBase inherits them via super.
# iter0_solver_options / iterk_solver_options below are
# read-only deprecated property shims over the layer fold.
# flags to complete the invariant
self.convobject = None # PH converger
self.attach_xbars()
# Whether PH_Prep has run. It refuses a second time: this object's W,
# rho and objective terms belong to one run. See PH_Prep.
self._PH_prep_done = False
# Set by keep_supplied_xbar_through_iter0.
self._xbar_supplied = False
# Set by request_PH_attach_before_iter0_solve.
self._attach_before_iter0_solve = False
# Whether this process's iteration-0 solve had the prox term on (an
# xbar was supplied and the terms were attached before that solve).
self._iter0_solved_with_prox = False
def _configure_slurm_deadline(self, options):
"""Set an opt-in monotonic deadline from Slurm's absolute end time.
Slurm counts from the allocation start, which can precede construction
of this object by hours. Converting its epoch timestamp to a local
``perf_counter`` deadline keeps later checks monotonic while preserving
the scheduler's actual clock origin.
"""
self._slurm_deadline = None
self._slurm_end_time = None
self._slurm_buffer_seconds = None
configured = options.get("slurm_buffer_seconds", None)
if configured is None:
return
try:
buffer_seconds = float(configured)
except (TypeError, ValueError) as exc:
raise ValueError(
"slurm_buffer_seconds must be a nonnegative number"
) from exc
if not math.isfinite(buffer_seconds) or buffer_seconds < 0:
raise ValueError(
"slurm_buffer_seconds must be a nonnegative finite number"
)
raw_end_time = os.environ.get("SLURM_JOB_END_TIME")
if raw_end_time is None:
raise RuntimeError(
"slurm_buffer_seconds was set, but SLURM_JOB_END_TIME is not "
"available. Use this option inside a Slurm allocation whose "
"environment exports the job end time."
)
try:
end_time = float(raw_end_time)
except ValueError as exc:
raise RuntimeError(
f"SLURM_JOB_END_TIME must be a Unix timestamp; got "
f"{raw_end_time!r}"
) from exc
if not math.isfinite(end_time):
raise RuntimeError(
"SLURM_JOB_END_TIME must be a finite Unix timestamp"
)
self._slurm_buffer_seconds = buffer_seconds
self._slurm_end_time = end_time
allocation_seconds_remaining = end_time - time.time()
hub_time_limit = allocation_seconds_remaining - buffer_seconds
self._slurm_deadline = time.perf_counter() + hub_time_limit
def _slurm_limit_message(self):
"""Describe the Slurm deadline using values current at log time."""
allocation_seconds_remaining = self._slurm_end_time - time.time()
hub_time_remaining = self._slurm_deadline - time.perf_counter()
end_text = time.strftime(
"%Y-%m-%d %H:%M:%S %Z", time.localtime(self._slurm_end_time)
)
return (
f"Slurm allocation: {allocation_seconds_remaining:.1f}s remaining "
f"(ends {end_text}); hub time limit: {hub_time_remaining:.1f}s "
f"({self._slurm_buffer_seconds:g}s shutdown buffer)"
)
def _local_time_limit_stop_reason(self):
"""Return the local soft-limit reason, or ``None`` before either limit."""
now = time.perf_counter()
deadlines = []
slurm_deadline = getattr(self, "_slurm_deadline", None)
if slurm_deadline is not None:
buffer_seconds = self._slurm_buffer_seconds
deadlines.append(
(slurm_deadline,
f"Slurm shutdown buffer of {buffer_seconds:g} seconds "
"reached.")
)
time_limit = self.options.get("time_limit", None)
if time_limit is not None:
deadlines.append(
(self.start_time + time_limit,
f"Time limit {time_limit} seconds reached.")
)
if deadlines:
deadline, reason = min(deadlines, key=lambda item: item[0])
if now >= deadline:
return reason
return None
@property
def iter0_solver_options(self):
"""Read-only fold of solver_options_layers for iteration 0.
Deprecated; reads emit a DeprecationWarning. Use
``_effective_solver_options(0)`` for the iter-0 fold, which is
the same value but doesn't go through the deprecation path.
"""
if self.cylinder_rank == 0:
warnings.warn(
"PHBase.iter0_solver_options is deprecated; call "
"_effective_solver_options(0) instead. Both return the "
"same fold of solver_options_layers.",
DeprecationWarning,
stacklevel=2,
)
return sputils.fold_solver_options_layers(
self.solver_options_layers, 0)
@property
def iterk_solver_options(self):
"""Read-only fold of solver_options_layers for iteration k>=1.
Deprecated; reads emit a DeprecationWarning. Use
``_effective_solver_options(k)`` for an exact per-iteration
fold (which can differ from k=1 when starting_at_iter layers
are present).
"""
if self.cylinder_rank == 0:
warnings.warn(
"PHBase.iterk_solver_options is deprecated; call "
"_effective_solver_options(k) for the exact fold at "
"iteration k. The property returns the fold at k=1 only.",
DeprecationWarning,
stacklevel=2,
)
return sputils.fold_solver_options_layers(
self.solver_options_layers, 1)
[docs]
def Compute_Xbar(self, verbose=False):
""" Gather xbar and x squared bar for each node in the list and
distribute the values back to the scenarios.
Args:
verbose (boolean):
If True, prints verbose output.
"""
_Compute_Xbar(self, verbose=verbose)
[docs]
def Update_W(self, verbose):
""" Update the dual weights during the PH algorithm.
Args:
verbose (bool):
If True, displays verbose output during update.
"""
# Assumes the scenarios are up to date
for k,s in self.local_scenarios.items():
for ndn_i, nonant in s._mpisppy_data.nonant_indices.items():
##if nonant._value == None:
## print(f"***_value is None for nonant var {nonant.name}")
xdiff = nonant._value \
- s._mpisppy_model.xbars[ndn_i]._value
s._mpisppy_model.W[ndn_i]._value += pyo.value(s._mpisppy_model.rho[ndn_i]) * xdiff
if verbose and self.cylinder_rank == 0:
print ("rank, node, scen, var, W", ndn_i[0], k,
self.cylinder_rank, nonant.name,
pyo.value(s._mpisppy_model.W[ndn_i]))
# Special code for variable probabilities to mask W; rarely used.
if s._mpisppy_data.has_variable_probability:
for ndn_i in s._mpisppy_data.nonant_indices:
(lndn, li) = ndn_i
s._mpisppy_model.W[ndn_i] *= s._mpisppy_data.prob0_mask[lndn][li]
[docs]
def Update_z(self, verbose):
""" Update the smoothing variable z during the PH algorithm.
Args:
verbose (bool):
If True, displays verbose output during update.
"""
# Assumes the scenarios are up to date
for k,s in self.local_scenarios.items():
for ndn_i, nonant in s._mpisppy_data.nonant_indices.items():
xzdiff = nonant._value \
- s._mpisppy_model.z[ndn_i]._value
s._mpisppy_model.z[ndn_i]._value += pyo.value(s._mpisppy_model.beta[ndn_i]) * xzdiff
if verbose and self.cylinder_rank == 0:
print ("rank, node, scen, var, z", ndn_i[0], k,
self.cylinder_rank, nonant.name,
pyo.value(s._mpisppy_model.z[ndn_i]))
[docs]
def convergence_diff(self):
""" Compute the convergence metric ||x_s - \\bar{x}||_1 / num_scenarios.
Returns:
float:
The convergence metric ||x_s - \\bar{x}||_1 / num_scenarios.
"""
# Every scenario has its own node list, with a vardata list
global_diff = np.zeros(1)
local_diff = np.zeros(1)
varcount = 0
for k,s in self.local_scenarios.items():
for ndn_i, nonant in s._mpisppy_data.nonant_indices.items():
xval = nonant._value
xdiff = xval - s._mpisppy_model.xbars[ndn_i]._value
local_diff[0] += abs(xdiff)
varcount += 1
local_diff[0] /= varcount
self.comms["ROOT"].Allreduce(local_diff, global_diff, op=MPI.SUM)
return global_diff[0] / self.n_proc
def _populate_W_cache(self, cache, padding):
""" Copy the W values for nonants *for all local scenarios*
Args:
cache (np vector) to receive the W's for all local scenarios (for sending)
NOTE: This is not the same as the nonant Vars because it puts all local W
values into the same cache and the cache is *not* attached to the scenario.
"""
ci = 0 # Cache index
for model in self.local_scenarios.values():
if (ci + len(model._mpisppy_data.nonant_indices)) >= len(cache):
tlen = len(model._mpisppy_data.nonant_indices) * len(self.local_scenarios)
raise RuntimeError("W cache length mismatch detected by "
f"{self.__class__.__name__} that has "
f"total W len {tlen} but passed cache len-1={len(cache)-1}; "
f"len(nonants)={len(model._mpisppy_data.nonant_indices)}")
for ix in model._mpisppy_data.nonant_indices:
cache[ci] = pyo.value(model._mpisppy_model.W[ix])
ci += 1
assert(ci == len(cache) - padding) # the other cylinder will fail above
[docs]
def W_from_flat_list(self, flat_list):
""" Set the dual weight values (Ws) for all local scenarios from a
flat list.
Args:
flat_list (list):
One-dimensional list of dual weights.
Warning:
We are counting on Pyomo indices not to change order between list
creation and use.
"""
ci = 0 # Cache index
for model in self.local_scenarios.values():
for ndn_i in model._mpisppy_data.nonant_indices:
model._mpisppy_model.W[ndn_i].value = flat_list[ci]
ci += 1
def _use_rho_setter(self, verbose):
""" set rho values using a function self.rho_setter
that gives us a list of (id(vardata), rho)]
"""
if self.rho_setter is None:
return
didit = 0
skipped = 0
rho_setter_kwargs = self.options['rho_setter_kwargs'] \
if 'rho_setter_kwargs' in self.options \
else dict()
for sname, scenario in self.local_scenarios.items():
rholist = self.rho_setter(scenario, **rho_setter_kwargs)
for (vid, rho) in rholist:
(ndn, i) = scenario._mpisppy_data.varid_to_nonant_index[vid]
if rho is None or rho <= 0:
vname = scenario._mpisppy_data.nonant_indices[(ndn, i)].name
raise RuntimeError(
f"rho_setter returned a non-positive rho for "
f"scenario={sname}, variable={vname}: rho={rho}. "
"Progressive Hedging requires rho > 0."
)
scenario._mpisppy_model.rho[(ndn, i)] = rho
didit += len(rholist)
skipped += len(scenario._mpisppy_data.varid_to_nonant_index) - didit
if verbose and self.cylinder_rank == 0:
print ("rho_setter set",didit,"and skipped",skipped)
def _disable_prox(self):
for k, scenario in self.local_scenarios.items():
scenario._mpisppy_model.prox_on = 0
if self.Ag is not None:
self.Ag.callout_agnostic({"scenario": scenario})
def _disable_W(self):
# It would be odd to disable W and not prox.
# TODO: we should eliminate this method
# probably not mathematically useful
for scenario in self.local_scenarios.values():
scenario._mpisppy_model.W_on = 0
if self.Ag is not None:
self.Ag.callout_agnostic({"scenario": scenario})
[docs]
def disable_W_and_prox(self):
self._disable_W()
self._disable_prox()
def _reenable_prox(self):
for k, scenario in self.local_scenarios.items():
scenario._mpisppy_model.prox_on = 1
if self.Ag is not None:
self.Ag.callout_agnostic({"scenario": scenario})
def _reenable_W(self):
# TODO: we should eliminate this method
for k, scenario in self.local_scenarios.items():
scenario._mpisppy_model.W_on = 1
if self.Ag is not None:
self.Ag.callout_agnostic({"scenario": scenario})
[docs]
def reenable_W_and_prox(self):
self._reenable_W()
self._reenable_prox()
[docs]
def post_solve_bound(self, solver_options=None, verbose=False):
''' Compute a bound Lagrangian bound using the existing weights.
Args:
solver_options (dict, optional):
Options for these solves.
verbose (boolean, optional):
If True, displays verbose output. Default False.
Returns:
float or None:
An outer bound on the optimal objective function value, or
None if any subproblem solve produced no bound (the
expectation cannot be formed if a scenario is missing one).
Note:
This function overwrites current variable values. This is only
suitable for use at the end of the solves, or if you really know
what you are doing. It is not suitable as a general, per-iteration
Lagrangian bound solver.
'''
if (self.cylinder_rank == 0):
print('Warning: Lagrangian bounds might not be correct in certain '
'cases where there are integers not subject to '
'non-anticipativity and those integers do not reach integrality.')
if (verbose and self.cylinder_rank == 0):
print('Beginning post-solve Lagrangian bound computation')
if (self.W_disabled):
self._reenable_W()
self._disable_prox()
# Fixed variables can lead to an invalid lower bound
self._restore_original_fixedness()
# If dis_prox=True, they are enabled at the end, and Ebound returns
# the incorrect value (unless you explicitly disable them again)
self.solve_loop(solver_options=solver_options,
dis_prox=False, # Important
gripe=True,
tee=False,
verbose=verbose,
warmstart=True,
)
bound = self.Ebound(verbose)
# A half-hearted attempt to restore the state
self._reenable_prox()
if (verbose and self.cylinder_rank == 0):
# bound is None if any subproblem produced no outer bound.
shown = "not available" if bound is None else f"{bound:.4f}"
print(f'Post-solve Lagrangian bound: {shown}')
return bound
[docs]
def solve_loop(self, solver_options=None,
dtiming=False,
dis_W=False,
dis_prox=False,
gripe=False,
disable_pyomo_signal_handling=False,
tee=False,
verbose=False,
need_solution=True,
warmstart=sputils.WarmstartStatus.FALSE,
*,
outer_bound_only=False):
""" Loop over `local_scenarios` and solve them in a manner
dictated by the arguments.
In addition to changing the Var values in the scenarios, this function
also updates the `_PySP_feas_indictor` to indicate which scenarios were
feasible/infeasible.
Args:
solver_options (dict, optional):
The scenario solver options.
dtiming (boolean, optional):
If True, reports solve timing information. Default is False.
dis_W (boolean, optional):
If True, duals weights (Ws) are disabled before solve, then
re-enabled after solve. Default is False.
dis_prox (boolean, optional):
If True, prox terms are disabled before solve, then
re-enabled after solve. Default is False.
gripe (boolean, optional):
If True, output a message when a solve fails. Default is False.
disable_pyomo_signal_handling (boolean, optional):
True for asynchronous PH; ignored for persistent solvers.
Default False.
tee (boolean, optional):
If True, displays solver output. Default False.
verbose (boolean, optional):
If True, displays verbose output. Default False.
need_solution (boolean, optional):
If True, raises an exception if a solution is not available.
Default True
warmstart (bool, optional):
If True, warmstart the subproblem solves. Default False.
outer_bound_only (boolean, optional):
If True, populate outer_bound *only*; no solution is loaded, so
need_solution must be False. If the solve reports no bound,
outer_bound is cleared to None rather than left at its previous
value: a stale bound cannot be mixed with fresh ones in the
expectation that Ebound forms.
Keyword-only. Default False.
"""
""" Developer notes:
This function assumes that every scenario already has a
`_solver_plugin` attached.
I am not sure what happens with solver_options None for a persistent
solver. Do options persist?
set_objective takes care of W and prox changes.
"""
if dis_W and dis_prox:
self.disable_W_and_prox()
elif dis_W:
self._disable_W()
elif dis_prox:
self._disable_prox()
if self._prox_approx and (not self.prox_disabled):
self._update_prox_approx()
super().solve_loop(
solver_options=solver_options,
dtiming=dtiming,
gripe=gripe,
disable_pyomo_signal_handling=disable_pyomo_signal_handling,
tee=tee,
verbose=verbose,
need_solution=need_solution,
outer_bound_only=outer_bound_only,
warmstart=warmstart,
)
if dis_W and dis_prox:
self.reenable_W_and_prox()
elif dis_W:
self._reenable_W()
elif dis_prox:
self._reenable_prox()
def _update_prox_approx(self):
"""
update proximal term approximation by potentially
adding a linear cut near each current xvar value
"""
tol = self.prox_approx_tol
for sn, s in self.local_scenarios.items():
persistent_solver = (s._solver_plugin if sputils.is_persistent(s._solver_plugin) else None)
#print(f"total number of proximal cuts: {len(s._mpisppy_model.xsqvar_cuts)}")
for prox_approx_manager in s._mpisppy_data.xsqvar_prox_approx.values():
if prox_approx_manager.xvar.value is None \
and not prox_approx_manager.xvar.fixed:
if self._PHIter != 0:
raise RuntimeError(
f"{prox_approx_manager.xvar.name} has no value at "
f"PH iteration {self._PHIter}, so the proximal "
"approximation has no point to cut at.")
# No solve has given this nonant a value yet: the prox
# term is on in iteration 0 because WXBarReader supplied
# xbar. Cut around xbar, where the prox term is centered.
prox_approx_manager.add_cuts(prox_approx_manager.xbar.value,
tol, persistent_solver)
continue
prox_approx_manager.check_tol_add_cut(tol, persistent_solver)
prox_approx_manager.xvarsqrd._value = prox_approx_manager.xvar.value**2
[docs]
def attach_Ws_and_prox(self):
""" Attach the dual and prox terms to the models in `local_scenarios`.
"""
for (sname, scenario) in self.local_scenarios.items():
# these are bound by index to the vardata list at the node
scenario._mpisppy_model.W = pyo.Param(scenario._mpisppy_data.nonant_indices.keys(),
initialize=0.0,
mutable=True)
# create ph objective terms, but disabled
scenario._mpisppy_model.W_on = pyo.Param(initialize=0, mutable=True, within=pyo.Binary)
scenario._mpisppy_model.prox_on = pyo.Param(initialize=0, mutable=True, within=pyo.Binary)
# note that rho is per var and scenario here. A None default is
# allowed here (e.g. when a rho_setter supplies every nonant); any
# nonant left without a positive rho is caught by check_rhos_positive
# after Iter0. An explicitly non-positive default is rejected now.
default_rho = self.options["defaultPHrho"]
if default_rho is not None and default_rho <= 0:
raise RuntimeError(
f"defaultPHrho must be a strictly positive number, got "
f"{default_rho}. Progressive Hedging requires rho > 0."
)
scenario._mpisppy_model.rho = pyo.Param(scenario._mpisppy_data.nonant_indices.keys(),
mutable=True,
default=default_rho)
if self.Ag is not None:
self.Ag.callout_agnostic({"sname":sname, "scenario":scenario})
[docs]
def attach_smoothing(self):
""" Attach the smoothing terms to the models in `local_scenarios`.
"""
for (sname, scenario) in self.local_scenarios.items():
scenario._mpisppy_model.z = pyo.Param(scenario._mpisppy_data.nonant_indices.keys(),
initialize=0.0,
mutable=True)
scenario._mpisppy_model.p = pyo.Param(scenario._mpisppy_data.nonant_indices.keys(),
mutable=True,
default=self.options["defaultPHp"])
scenario._mpisppy_model.beta = pyo.Param(scenario._mpisppy_data.nonant_indices.keys(),
mutable=True,
default=self.options["defaultPHbeta"])
@property
def W_disabled(self):
assert hasattr(self.local_scenarios[self.local_scenario_names[0]]._mpisppy_model, 'W_on')
return not bool(self.local_scenarios[self.local_scenario_names[0]]._mpisppy_model.W_on.value)
@property
def prox_disabled(self):
assert hasattr(self.local_scenarios[self.local_scenario_names[0]]._mpisppy_model, 'prox_on')
return not bool(self.local_scenarios[self.local_scenario_names[0]]._mpisppy_model.prox_on.value)
def _prox_is_quadratic(self):
"""True when subproblem objectives carry a (non-linearized) quadratic
proximal term, i.e. the prox term is attached and active and is not
being approximated by linear cuts. This is exactly the condition under
which a solver that cannot handle a quadratic objective will fail.
"""
return (not self._prox_approx) and (not self.prox_disabled)
def _first_prox_solve(self):
"""True during this process's first solve with the prox term on: the
iteration-0 solve when an xbar was supplied (see
request_PH_attach_before_iter0_solve), otherwise the first iteration
of this leg -- iteration 1, or the first one after a resume, which may
legitimately have switched solvers.
"""
if self._PHIter == 0:
return self._iter0_solved_with_prox
return (self._PHIter == self._resume_iteration + 1
and not self._iter0_solved_with_prox)
def _check_prox_solver_capability(self):
"""Proactive half of the quadratic-prox/solver compatibility check.
If the solver reports (via the legacy ``has_capability`` API) that it
cannot handle a quadratic objective, fail immediately with an
actionable message rather than letting the first proximal solve fail
cryptically. Solvers that do not expose capability information (e.g.
HiGHS via the APPSI or ``pyomo.contrib.solver`` interfaces) are left to
the reactive check after the first solve.
The decision is deterministic and identical on every rank (same
``solver_name``), so raising here cannot desynchronize MPI.
"""
if not self._prox_is_quadratic():
return
# All subproblems share solver_name, so one probe is representative.
s = next(iter(self.local_scenarios.values()))
if sputils.solver_quadratic_objective_capability(s._solver_plugin) is False:
raise RuntimeError(
f"Solver '{self.options.get('solver_name')}' reports that it "
"cannot handle a quadratic objective, which the Progressive "
"Hedging proximal term requires. " + _LINEARIZE_PROX_HINT
)
def _check_prox_solve_succeeded(self):
"""Reactive half of the quadratic-prox/solver compatibility check.
After the first proximal (quadratic) solve, if no subproblem anywhere
produced a solution, the most likely cause is a solver that cannot
handle a quadratic objective but does not report it through
``has_capability`` (e.g. HiGHS, which cannot solve an MIQP). Emit an
actionable message instead of leaving the user with the cryptic
``TerminationCondition=unknown`` from the failed solve.
Restricted to the first solve of this process with the prox term on
(see ``_first_prox_solve``): iteration 0 when an xbar was supplied,
otherwise iteration 1 or the first iteration after a resume, which may
legitimately be running a different solver (``solver_name`` is
deliberately exempt from the resume fingerprint). If that solve
succeeds, the solver supports quadratic objectives, so any later
failure is a genuine optimization issue rather than a capability
problem. The "no solution anywhere" test is reduced across ranks with
``allreduce_or`` so the raise decision is identical on every rank (no
MPI desynchronization);
a partial failure (some subproblems still solve) falls through to the
existing behavior.
"""
if not (self._first_prox_solve() and self._prox_is_quadratic()):
return
local_any_solution = any(
s._mpisppy_data.solution_available
for s in self.local_scenarios.values()
)
if self.allreduce_or(local_any_solution):
return
raise RuntimeError(
f"No subproblem produced a solution at PH iteration "
f"{self._PHIter} while a quadratic proximal term was active. "
f"Solver '{self.options.get('solver_name')}' may not support "
"quadratic objectives (e.g. HiGHS cannot solve an MIQP). "
+ _LINEARIZE_PROX_HINT
)
def _reraise_as_prox_capability_error(self, exc):
"""Wrap a raised first-solve error as an actionable capability message.
Completes the quadratic-prox/solver compatibility checks for solvers
that signal "cannot handle a quadratic objective" by *raising* during
the solve rather than returning without a solution. cbc and glpk are the
motivating case: their LP writer raises before the reactive
``_check_prox_solve_succeeded`` can run, and the proactive
``has_capability`` probe does not always catch them (the capability is
reported inconsistently across Pyomo versions / solver interfaces).
Only the first quadratic solve of this process is treated this way
(see ``_first_prox_solve``); a raise at a later iteration is a
genuine solve error and is left to propagate unchanged. When
applicable this raises a new ``RuntimeError`` chained from ``exc``
(so the original traceback is preserved); otherwise it returns and the
caller re-raises ``exc`` as-is. The guard matches the reactive check, so
MPI synchronization is unchanged beyond the raise that already occurred.
"""
if not (self._first_prox_solve() and self._prox_is_quadratic()):
return
raise RuntimeError(
f"Solver '{self.options.get('solver_name')}' raised an error on the "
"first solve with a quadratic proximal term active, which it may "
"not support (e.g. cbc/glpk cannot write a quadratic objective to "
"LP format). " + _LINEARIZE_PROX_HINT
) from exc
[docs]
def attach_PH_to_objective(self, add_duals, add_prox, add_smooth=0):
""" Attach dual weight and prox terms to the objective function of the
models in `local_scenarios`.
Args:
add_duals (boolean):
If True, adds dual weight (Ws) to the objective.
add_prox (boolean):
If True, adds the prox term to the objective.
"""
if ('linearize_binary_proximal_terms' in self.options):
lin_bin_prox = self.options['linearize_binary_proximal_terms']
else:
lin_bin_prox = False
if ('linearize_proximal_terms' in self.options):
self._prox_approx = self.options['linearize_proximal_terms']
if 'proximal_linearization_tolerance' in self.options:
self.prox_approx_tol = self.options['proximal_linearization_tolerance']
else:
self.prox_approx_tol = 1.e-1
# The proximal approximation code now checks the tolerance based on the x-coordinates
# as opposed to the y-coordinates. Therefore, we will use the square root of the
# y-coordinate tolerance.
self.prox_approx_tol = math.sqrt(self.prox_approx_tol)
else:
self._prox_approx = False
for (sname, scenario) in self.local_scenarios.items():
"""Attach the dual and prox terms to the objective.
"""
if ((not add_duals) and (not add_prox)):
return
objfct = self.saved_objectives[sname]
is_min_problem = objfct.is_minimizing()
xbars = scenario._mpisppy_model.xbars
if self._prox_approx:
# set-up pyomo IndexVar, but keep it sparse
# since some nonants might be binary
# Define the first cut to be _xsqvar >= 0
scenario._mpisppy_model.xsqvar = pyo.Var(scenario._mpisppy_data.nonant_indices, dense=False, bounds=(0, None), initialize=0.0)
scenario._mpisppy_model.xsqvar_cuts = pyo.Constraint(scenario._mpisppy_data.nonant_indices, pyo.Integers)
scenario._mpisppy_data.xsqvar_prox_approx = {}
try:
scenario._mpisppy_data.nonant_cost_coeffs = sputils.nonant_cost_coeffs(scenario)
except sputils.NonLinearProblemFound:
raise RuntimeError("The proximal term approximation can only be used with a linear objective function")
else:
scenario._mpisppy_model.xsqvar = None
scenario._mpisppy_data.xsqvar_prox_approx = False
ph_term = 0
# Dual term (weights W)
if (add_duals):
scenario._mpisppy_model.WExpr = pyo.Expression(expr=\
sum(scenario._mpisppy_model.W[ndn_i] * xvar \
for ndn_i, xvar in scenario._mpisppy_data.nonant_indices.items()) )
ph_term += scenario._mpisppy_model.W_on * scenario._mpisppy_model.WExpr
# Prox term (quadratic)
if (add_prox):
prox_expr = 0.
smooth_expr = 0.
for ndn_i, xvar in scenario._mpisppy_data.nonant_indices.items():
# expand (x - xbar)**2 to (x**2 - 2*xbar*x + xbar**2)
# x**2 is the only qradratic term, which might be
# dealt with differently depending on user-set options
if xvar.is_binary() and (lin_bin_prox or self._prox_approx):
xvarsqrd = xvar
elif self._prox_approx:
xvarsqrd = scenario._mpisppy_model.xsqvar[ndn_i]
scenario._mpisppy_data.xsqvar_prox_approx[ndn_i] = \
ProxApproxManager(scenario, xvar, ndn_i)
else:
xvarsqrd = xvar**2
prox_expr += (scenario._mpisppy_model.rho[ndn_i] / 2.0) * \
(xvarsqrd - 2.0 * xbars[ndn_i] * xvar + xbars[ndn_i]**2)
# Computing smoothing term (quadratic)
if (add_smooth):
smooth_expr += (scenario._mpisppy_model.p[ndn_i] / 2.0) * \
(xvarsqrd - 2.0 * scenario._mpisppy_model.z[ndn_i] * xvar \
+ scenario._mpisppy_model.z[ndn_i]**2)
scenario._mpisppy_model.ProxExpr = pyo.Expression(expr=prox_expr)
ph_term += scenario._mpisppy_model.prox_on * scenario._mpisppy_model.ProxExpr
if (add_smooth):
# Adding smoothing term
scenario._mpisppy_model.SmoothExpr = pyo.Expression(expr=smooth_expr)
ph_term += scenario._mpisppy_model.prox_on * scenario._mpisppy_model.SmoothExpr
if (is_min_problem):
objfct.expr += ph_term
else:
objfct.expr -= ph_term
if self.Ag is not None:
self.Ag.callout_agnostic({"sname":sname, "scenario":scenario,
"add_duals": add_duals, "add_prox": add_prox})
[docs]
def keep_supplied_xbar_through_iter0(self):
""" Tell Iter0 that an extension set xbar in pre_iter0 (WXBarReader
reading --init-Xbar-fname, for example), so Iter0 must not replace it
with the mean of the iteration-0 solutions. The rho setters that run
in post_iter0 (SepRho, SensiRho, GradRho) then measure the iteration-0
solutions against the supplied xbar. Iteration 1 computes xbar from
the solutions as usual.
"""
self._xbar_supplied = True
[docs]
def request_PH_attach_before_iter0_solve(self):
""" Ask Iter0 to splice the W and prox terms into the objectives
before the iteration-0 solve rather than after it, so that solve uses
whatever W (and xbar) an extension set in pre_iter0 -- WXBarReader,
for example. Iter0 does the splice once every pre_iter0 hook has run
and before it creates the solvers.
With the terms attached, the iteration-0 objective values give a
Lagrangian bound for the supplied W rather than the trivial bound.
Has no effect when the terms were attached in PH_Prep
(defer_attach=False) or the run resumed from a checkpoint.
"""
self._attach_before_iter0_solve = True
def _attach_PH_to_objective_after_iter0(self):
""" Splice the W/prox terms into the objective after the iteration-0
solve, and refresh any persistent solvers.
``attach_PH_to_objective`` mutates each subproblem objective and, in
prox-approximation mode, also adds the ``xsqvar`` variable plus its cut
constraints. Because the subproblem solvers were already created (and
persistent solvers had ``set_instance`` called) on the user's original
objective during Iter0, a persistent solver does not see these later
changes; we re-run ``set_instance`` so the new terms and components
reach the solver. Non-persistent solvers re-read the model on the next
solve, so they need nothing here.
"""
self.attach_PH_to_objective(self._attach_duals,
self._attach_prox,
self._attach_smooth)
if (not self._attach_duals) and (not self._attach_prox):
# attach_PH_to_objective made no change to the objective
# (e.g. APH passes both flags False); nothing to re-push.
return
for sname, s in self.local_scenarios.items():
if sputils.is_persistent(s._solver_plugin):
mpisppy.spopt.set_instance_retry(s, s._solver_plugin, sname)
[docs]
def PH_Prep(
self,
attach_duals=True,
attach_prox=True,
attach_smooth=0,
defer_attach=True,
):
""" Set up PH objectives (duals and prox terms), and prepare
extensions, if available.
Args:
attach_duals (boolean, optional):
If True, adds dual weight (Ws) to the objective. Default True.
attach_prox (boolean, optional):
If True, adds prox terms to the objective. Default True.
attach_smooth (int, optional):
If 0, no smoothing; if 1, p_value is used; if 2, p_ratio is used.
defer_attach (boolean, optional):
If True (default), the W and prox terms are not spliced into
the subproblem objectives here; instead they are attached at
the end of Iter0 (see _attach_PH_to_objective_after_iter0) so
that the iteration-0 solve uses exactly the user's objective --
no PH machinery in the expression tree. If False, the terms are
attached immediately (legacy behavior, needed by FWPH, which
snarfs the subproblem objective between PH_Prep and Iter0).
Agnostic (AML guest) runs are always attached immediately
regardless of this flag (the guest builds its xbars Param in
the attach callout, which solve_one needs from iteration 0).
Note:
This function constructs an Extension object if one was specified
at the time the PH object was created.
Note:
PH_Prep may be run only once on an object, so a PH object solves
one problem. Running PH_Prep twice used to look like it worked and
quietly solve something else: attach_Ws_and_prox re-declared W and
rho as fresh Params, discarding the duals the first run produced,
and attach_PH_to_objective appended a *second* PH term to the same
objective, leaving the first live and anchored to the previous
run's xbar. Measured on farmer, W went from
[8.374, 33.574, -41.948] to [0.0, 0.0, 0.0] and the objective's
W_on count from 1 to 2, with no error and no warning.
Making it genuinely re-entrant is possible but is not free -- see
issue #848 -- and no caller wants it: every one that runs PH more
than once builds a new object.
"""
if self._PH_prep_done:
raise RuntimeError(
"PH_Prep has already been run on this object. A PH object "
"solves one problem: W, rho and the objective terms it "
"carries belong to that run, and a second prep would discard "
"the first and double the terms. Build a new object.")
self.attach_Ws_and_prox()
if attach_smooth:
self.attach_smoothing()
# attach_PH_to_objective sets self._prox_approx; when the attach is
# deferred it has not run yet, but the iteration-0 solve_loop reads
# this flag. Prox terms (and any prox approximation) are structurally
# absent in iteration 0, so the flag must read False there regardless.
self._prox_approx = False
# Remember what to attach and whether it was deferred, so Iter0 can
# splice the terms in after the iteration-0 solve.
self._attach_duals = attach_duals
self._attach_prox = attach_prox
self._attach_smooth = attach_smooth
# Agnostic (AML) guests build the W/prox terms -- including the guest
# xbars Param that solve_one copies into on every solve -- inside the
# guest's attach_PH_to_objective callout, which must run before the
# iteration-0 solve. The deferral is therefore not applied to agnostic
# runs; they keep the legacy attach-in-PH_Prep behavior.
self._deferred_ph_attach = defer_attach and (self.Ag is None)
if not self._deferred_ph_attach:
self.attach_PH_to_objective(attach_duals, attach_prox, attach_smooth)
# Last, so a prep that raised leaves the object unprepped and the
# retry reports the real failure, not "already been run".
self._PH_prep_done = True
[docs]
def options_check(self):
""" Check whether the options in the `options` attribute are
acceptable.
Required options are
- solver_name (string): The name of the solver to use.
- PHIterLimit (int): The maximum number of PH iterations to execute.
- defaultPHrho (float): The default value of rho (penalty parameter) to
use for PH.
- convthresh (float): The convergence tolerance of the PH algorithm.
- verbose (boolean): Flag indicating whether to display verbose output.
- display_progress (boolean): Flag indicating whether to display
information about the progression of the algorithm.
- iter0_solver_options (dict): Dictionary of solver options to use on
the first solve loop.
- iterk_solver_options (dict): Dictionary of solver options to use on
subsequent solve loops (after iteration 0).
"""
required = [
"solver_name", "PHIterLimit", "defaultPHrho",
"convthresh", "verbose", "display_progress",
]
self._options_check(required, self.options)
# Display timing and display convergence detail are special for no good reason.
if "display_timing" not in self.options:
self.options["display_timing"] = False
if "display_convergence_detail" not in self.options:
self.options["display_convergence_detail"] = False
# Smoothed is optional, not required
if "smoothed" not in self.options:
self.options["smoothed"] = 0
# time_limit is optional, not required
if "time_limit" not in self.options:
self.options["time_limit"] = None
def _can_update_best_bound(self):
if not self.prox_disabled:
return False
return super()._can_update_best_bound()
def _iter0_use_pickled_solution(self):
"""Skip the iter0 solve loop and trust the values baked into the pickle.
Companion to ``--iter0-before-pickle`` (the pre-pickle pipeline that
solves each scenario / bundle once with its original objective and
stores variable values + duals inside the pickle). When the user
also passes ``--iter0-from-pickle``, this routine takes the place of
``solve_loop`` for iteration 0:
- Validate that every local scenario actually carries the
``pickle_metadata['iter0_before_pickle'] == True`` flag set by
the pre-pickle pipeline. Hard-fail otherwise; we will not
fabricate solver state.
- Set the per-scenario bookkeeping that ``solve_loop`` would have
set: ``solution_available``, ``outer_bound``, ``inner_bound``.
The bounds are the solver's reported ``Lower_bound`` /
``Upper_bound`` captured at pickle time (see
``generic/scenario_io.py::_solve_iter0_for_pickle``) -- that
preserves the outer/inner split for MIPs solved with a
nonzero gap. The variable values themselves are already in
place from the pickle, so PH's downstream logic (xbar, W
update, etc.) just works.
See doc/src/pickling.rst for the user-facing description.
"""
global_toc("Skipping PHBase.Iter0 solve loop "
"(--iter0-from-pickle); using values from pickle")
missing = []
missing_bounds = []
for sname, s in self.local_scenarios.items():
md = getattr(s._mpisppy_data, "pickle_metadata", None)
if not md or not md.get("iter0_before_pickle", False):
missing.append(sname)
continue
if ("iter0_outer_bound" not in md
or "iter0_inner_bound" not in md):
missing_bounds.append(sname)
if missing:
sample = ", ".join(missing[:3])
more = "..." if len(missing) > 3 else ""
raise RuntimeError(
f"--iter0-from-pickle was set, but {len(missing)} local "
f"scenario(s) on rank {self.cylinder_rank} do not carry an "
f"iter0 solution from pickle time ({sample}{more}). "
f"Re-pickle with --iter0-before-pickle, or remove "
f"--iter0-from-pickle."
)
if missing_bounds:
sample = ", ".join(missing_bounds[:3])
more = "..." if len(missing_bounds) > 3 else ""
raise RuntimeError(
f"--iter0-from-pickle was set, but {len(missing_bounds)} "
f"local scenario(s) on rank {self.cylinder_rank} have "
f"iter0 pickle metadata without captured outer/inner "
f"bounds ({sample}{more}). This pickle was written with "
f"an older metadata format; re-pickle with the current "
f"--iter0-before-pickle."
)
for sname, s in self.local_scenarios.items():
md = s._mpisppy_data.pickle_metadata
s._mpisppy_data.solution_available = True
s._mpisppy_data.outer_bound = md["iter0_outer_bound"]
s._mpisppy_data.inner_bound = md["iter0_inner_bound"]
def _restore_prox_approx_state(self):
"""Set the prox-approximation state that the skipped attach would have.
``attach_PH_to_objective`` does two separable things: it mutates the
subproblem objectives, and it records on *this object* whether the
proximal term is being linearized and at what tolerance. A resume must
skip the first (the reloaded model already carries the spliced
objective and its cuts) but still needs the second: ``_prox_approx``
gates ``_update_prox_approx``, so leaving it False means no new cut is
ever added and the resumed run stays frozen on the checkpoint's cut
set, drifting further out of tune as x moves. It also feeds
``_prox_is_quadratic``, which decides whether to reject an LP-only
solver -- exactly the solver a linearized run is likely using.
Kept in step with the corresponding block of ``attach_PH_to_objective``.
"""
if not self.options.get("linearize_proximal_terms", False):
self._prox_approx = False
return
self._prox_approx = True
self.prox_approx_tol = self.options.get(
"proximal_linearization_tolerance", 1.e-1)
# The tolerance is applied to x-coordinates, so it is the square root
# of the y-coordinate tolerance the user supplied.
self.prox_approx_tol = math.sqrt(self.prox_approx_tol)
def _release_scenario_creator_held_models(self, models):
"""Tell whoever built the scenarios that a resume replaced them.
Most ``scenario_creator``s are plain functions that hand a model over
and forget it, so this does nothing. The ADMM paths are the exception
(design section 8.2, item 2): their creator is a bound method of a
wrapper or bundler that keeps its own references to every model it
built. Those references outlive the swap, so without this a resumed
ADMM run holds two copies of every local scenario -- the reloaded ones
it iterates and the fresh ones it does not -- for the rest of the run,
which on large MIPs is precisely the memory a checkpoint exists to
save.
Duck-typed on purpose: the holder knows which of its attributes point
at models, and asking it is what keeps that knowledge in one place
instead of spreading a list of wrapper internals through the resume
branch.
"""
holder = getattr(getattr(self, "scenario_creator", None),
"__self__", None)
release = getattr(holder, "release_scenario_models", None)
if release is not None:
release(models)
def _restore_extension_state_if_resuming(self):
"""Hand every extension and the converger their checkpointed state.
Called at the very end of ``Iter0``, and the timing is the whole
point. Extensions rebuild their bookkeeping from the models in
``pre_iter0``/``post_iter0`` -- ``Fixer.populate`` and
``Slammer.pre_iter0`` both do -- so restoring any earlier would simply
have it overwritten by setup that thinks the run is starting. The
converger is later still: ``Iter0`` constructs it a few lines above
here, so this is the first moment it exists to restore into.
A no-op on a run that is not resuming, and on a resumed run whose
extensions have no state of their own.
"""
if not self._resumed_from_checkpoint:
return
state = self._checkpoint_leaf_state.get("extension_state")
rank0 = self.cylinder_rank == 0
# Agreed, like every other step of a restore: an extension puts its
# state back on the models *this* rank owns, so one that cannot is a
# refusal one rank makes alone -- and the iteration waiting after this
# is collective. An extension's restore_state must therefore not be
# collective itself; the hook says so.
messages = checkpointing.run_agreed(
self, lambda: checkpointing.restore_extension_state(self, state),
"hand their extensions the checkpointed state, so none of them "
"resumes")
for message in messages:
global_toc(f"WARNING: {message}", rank0)
def _require_state_contract_if_checkpointing(self):
"""Refuse, before anything is solved, a checkpointed run that would
fail at its first checkpoint write or at its resume.
Called at the start of ``Iter0``. The extensions are constructed by
then and the converger class is known, which is all the check reads.
Hub only. The xhat spokes write their extensions' state too, and the
Checkpointer checks theirs in its pre_iter0; the dual cylinders write
W and no extension state.
"""
if not (self.options.get("checkpoint_dir", None)
or self.options.get("resume_from", None)):
return
from mpisppy.opt.ph import PH
if not isinstance(self, PH):
return
checkpointing.require_state_contract(self)
def _restore_from_checkpoint_if_resuming(self):
"""Splice a checkpoint's scenario models into this run, if resuming.
Called from ``Iter0`` before ``_create_solvers``. A no-op unless
``--resume-from`` was given. See
``doc/designs/checkpointing_design.md`` sections 5.1 and 9.
"""
ckpt_dir = self.options.get("resume_from", None)
if not ckpt_dir:
return
# A dual cylinder runs PH without being the hub, and the hub's
# checkpoint is not its: splicing the hub's scenarios in here would
# replace this cylinder's models with a copy of another cylinder's.
# It restores its own W instead, in Checkpointer.post_iter0.
if self.options.get("checkpoint_role", "hub") != "hub":
return
# The write side refuses non-PH hubs (Checkpointer.__init__), and this
# is its read-side counterpart. Without it, `--APH --resume-from`
# splices a PH checkpoint into APH with no error at startup: APH has
# already attached its own y/ybars/z Params to the models this splice
# discards, and its loop iterates a hardcoded range(1, ...) that
# ignores the resume offset.
from mpisppy.opt.ph import PH
if not isinstance(self, PH):
raise RuntimeError(
f"--resume-from currently supports the synchronous PH hub "
f"only, but this hub is {type(self).__name__}. Remove "
f"--resume-from, or run PH."
)
# Also the read-side counterpart of the Checkpointer's backend
# refusal, for a resume that runs without one attached: without it,
# `--resume-from ckpt --checkpoint-backend leaf` would go ahead on the
# manifest's backend and ignore the one it was asked for.
checkpointing.require_implemented_backend(
self.options.get("checkpoint_backend",
checkpointing.DILL_RELOAD_BACKEND))
# The splice below is this rank's own work from end to end: it reads
# the file named after this rank and checks it against the scenarios
# this rank owns, so it refuses on the ranks the checkpoint does not
# match and returns on the others. The next thing Iter0 does is
# collective, so a rank-local refusal would leave the rest of the
# cylinder waiting for a rank that has already gone -- the resume
# would hang instead of refusing. Every rank refuses or none does.
checkpointing.run_agreed(
self, lambda: self._splice_checkpoint(ckpt_dir),
"restore the checkpoint into this run, so none of them resumes")
def _splice_checkpoint(self, ckpt_dir):
"""Load this rank's checkpoint and put it in place of the fresh run.
Local by nature and agreed by the caller; see
``checkpointing.run_agreed``. Nothing in here may be collective, for
the same reason: the ranks it would synchronize have not agreed yet
that they are all still here.
"""
leaf, models = checkpointing.load_checkpoint(self, ckpt_dir)
for sname, model in models.items():
self.local_scenarios[sname] = model
# Eobjective/Ebound read these objective handles; left alone they
# would dangle to the fresh model we just replaced.
self.saved_objectives[sname] = sputils.find_active_objective(model)
# The recourse values came back with the model, so the first
# resumed solve can warm-start from them -- but only if the run
# asked for warm starts at all: solve_one consults this flag only
# when options["warmstart_subproblems"] is set, and that defaults
# to False. Setting it here is what makes --warmstart-subproblems
# work across a resume; on its own it changes nothing.
model._mpisppy_data.solution_available = True
# The generic file-based path keeps this alias and CGBase.solve_loop
# iterates it; a plain PH has no such attribute.
if getattr(self, "local_subproblems", None) is not None:
self.local_subproblems = self.local_scenarios
self._release_scenario_creator_held_models(models)
# varid_to_nonant_index maps id(vardata) -> (ndn, i). dill faithfully
# brings the dict back, and every key in it is dead: the integers are
# the addresses of the objects that were serialized, which say nothing
# about the objects that came out. So it survives the round trip
# looking perfectly intact while mapping nothing, and a consumer gets
# a KeyError on an id it just took from a live variable.
#
# It is the same identity-keying hazard as the initially-fixed
# baseline below and ADMM's varprob_dict, and the one that hides
# longest: the rho setter is skipped on a resume and the other
# consumers are optional, so the first thing to trip over it was the
# fixer -- several phases in.
self._attach_varid_to_nonant_index()
# _initial_fixed_varibles is a ComponentSet of vardata belonging to the
# models we just discarded, so every reloaded nonant would look
# unrecognized and _can_update_best_bound would refuse to update the
# bound for the rest of the run. Rebuilding it from the checkpointed
# *names* also keeps nonants that a fixing extension pinned mid-run
# from passing as originally fixed, which would let through a bound the
# uninterrupted run would have refused.
self._restore_fixed_nonant_baseline(leaf["initially_fixed_nonants"])
# The deferred attach runs at the end of Iter0, downstream of here. The
# reloaded model already carries the spliced objective and the prox
# cuts, so letting it run would double the W terms and duplicate the
# prox components.
self._deferred_ph_attach = False
# But that call also sets state on *this object*, not just on the
# models, and skipping it would leave the run without it: _prox_approx
# gates whether new proximal-approximation cuts get added at all, so a
# resumed run would be frozen on the checkpoint's cut set for good.
self._restore_prox_approx_state()
self._checkpoint_leaf_state = leaf
self._resumed_from_checkpoint = True
self._resume_iteration = int(leaf["generation"])
# Start the counter at the checkpointed iteration rather than 0. If the
# resumed loop turns out to have nothing to do -- the user resumed
# without raising --max-iterations -- _PHIter must still read as the
# iteration we are actually at, or a terminal write would republish the
# run as generation 0 and delete the real checkpoint.
self._PHIter = self._resume_iteration
global_toc(f"Resuming from checkpoint in {ckpt_dir} "
f"(iteration {self._resume_iteration})",
self.cylinder_rank == 0)
[docs]
def Iter0(self):
""" Create solvers and perform the initial PH solve (with no dual
weights or prox terms, unless an extension called
request_PH_attach_before_iter0_solve).
This function quits() if the scenario probabilities do not sum to one,
or if any of the scenario subproblems are infeasible. It also calls the
`post_iter0` method of any extensions, and uses the rho setter (if
present) after the initial solve.
Returns:
float:
The so-called "trivial bound", i.e., the objective value of the
stochastic program with the nonanticipativity constraints
removed.
"""
verbose = self.options["verbose"]
dprogress = self.options["display_progress"]
dtiming = self.options["display_timing"]
dconvergence_detail = self.options["display_convergence_detail"]
smooth_type = self.options["smoothed"]
have_extensions = self.extensions is not None
have_converger = self.ph_converger is not None
def _vb(msg):
if verbose and self.cylinder_rank == 0:
print("(rank0)", msg)
self._PHIter = 0
self._save_original_nonants()
self._require_state_contract_if_checkpointing()
# Resume, if asked: swap the checkpointed models in *before* solvers
# are created, so _create_solvers attaches a solver (and, for a
# persistent solver, calls set_instance) to the reloaded model rather
# than to one we are about to discard. Doing it the other way round
# makes every scenario pay set_instance twice per resume, which for
# large MIPs is exactly the cost checkpointing is meant to avoid.
self._restore_from_checkpoint_if_resuming()
# pre_iter0 runs after the restore so extensions act on the models the
# run will actually iterate. Before the splice, anything a hook did to
# the fresh models -- WXBarReader loading --init-W-fname, say -- was
# silently discarded with them, and any bookkeeping the hook kept
# pointed at dead models.
if have_extensions:
self.extobject.pre_iter0()
# After pre_iter0 rather than inside the hook that asked for it:
# SepRho and CoeffRho read cost coefficients from the objective in
# their pre_iter0, and a W term already there would add to them.
# Before _create_solvers, so a persistent solver sees the terms
# without a second set_instance.
if getattr(self, "_deferred_ph_attach", False) \
and self._attach_before_iter0_solve:
self.attach_PH_to_objective(self._attach_duals,
self._attach_prox,
self._attach_smooth)
self._deferred_ph_attach = False
global_toc("Creating solvers")
self._create_solvers()
if (self.extensions is not None):
self.extobject.iter0_post_solver_creation()
teeme = ("tee-rank0-solves" in self.options
and self.options['tee-rank0-solves']
and self.cylinder_rank == 0
)
if self._resumed_from_checkpoint:
# The reloaded models already carry a solved iterate; re-solving
# them here with W = 0 would discard it. Bookkeeping that
# solve_loop would have set was restored with the models.
global_toc("Skipping PHBase.Iter0 solve loop (--resume-from); "
"continuing from the checkpointed iterate")
elif self.options.get("iter0_from_pickle", False):
self._iter0_use_pickled_solution()
else:
if self.options["verbose"]:
print (f"About to call PH Iter0 solve loop on rank={self.cylinder_rank}")
global_toc("Entering solve loop in PHBase.Iter0")
# PH's prox term is in the objective here only if it was attached
# before this solve, and on only if an extension supplied xbar.
# The same on every rank: it follows from the files read. (APH
# adds its own prox term instead, which this does not see.)
prox_attached = (getattr(self, "_attach_prox", False)
and not getattr(self, "_deferred_ph_attach", False))
self._iter0_solved_with_prox = prox_attached and not self.prox_disabled
if self._iter0_solved_with_prox:
self._check_prox_solver_capability()
try:
self.solve_loop(solver_options=self._effective_solver_options(self._PHIter),
dtiming=dtiming,
gripe=True,
tee=teeme,
verbose=verbose,
warmstart=sputils.WarmstartStatus.USER_SOLUTION,
)
except Exception as e:
self._reraise_as_prox_capability_error(e)
raise
if self._iter0_solved_with_prox:
self._check_prox_solve_succeeded()
if self.options["verbose"]:
print (f"PH Iter0 solve loop complete on rank={self.cylinder_rank}")
self._update_E1() # Apologies for doing this after the solves...
if (abs(1 - self.E1) > self.E1_tolerance):
raise RuntimeError(f"Total probability of scenarios was {self.E1}; E1_tolerance = ", self.E1_tolerance)
feasP = self.incumbent_prob()
if feasP != self.E1:
raise RuntimeError(f"Infeasibility detected; E_feas={feasP}, E1={self.E1}")
"""
with open('mpi.out-{}'.format(rank), 'w') as fd:
for sname in self.local_scenario_names:
fd.write('*** {} ***\n'.format(sname))
"""
#global_toc('Rank: {} - Building and solving models 0th iteration'.format(rank), True)
#global_toc('Rank: {} - assigning rho'.format(rank), True)
# PH itself first computes xbar at the top of iteration 1, but the
# post_iter0 hooks need it now: SepRho, SensiRho and GradRho set rho
# from |x - xbar|, and the dynamic-rho caches start from it. Without
# this they see the xbars Param's initial 0. A resumed run's xbar came
# with the checkpoint, and a supplied one is kept on purpose.
if not self._resumed_from_checkpoint and not self._xbar_supplied:
self.Compute_Xbar(verbose)
if have_extensions:
self.extobject.post_iter0()
if self._resumed_from_checkpoint:
# The trivial bound belongs to iteration 0 of the original run;
# recomputing it here would use the checkpointed (W-laden) iterate
# and produce something that is not the trivial bound at all.
self.trivial_bound = self._checkpoint_leaf_state["trivial_bound"]
restored_bound = self._checkpoint_leaf_state["best_bound_obj_val"]
if restored_bound is not None:
self.best_bound_obj_val = restored_bound
# The best outer bound may have come from a spoke (for example a
# Lagrangian bound), which best_bound_obj_val never sees. Put it
# back where the hub keeps it, or the resumed run reports whatever
# the restarted spokes find next, which can be worse.
restored_outer = self._checkpoint_leaf_state["best_outer_bound"]
if restored_outer is not None and self.spcomm is not None:
self.spcomm.BestOuterBound = \
self.spcomm.OuterBoundUpdate(restored_outer)
# Likewise the inner bound, which an xhat spoke sent. The hub
# first reads its spokes' bounds after the first resumed
# iteration's solve, so without this that iteration runs against
# an infinite inner bound -- gap tests that cannot fire, and a
# Gapper mipgap set as if nothing had been found -- where the
# uninterrupted run had the incumbent. Each bound is credited to
# the spoke whose file it came from: that spoke restores the
# solution and republishes the same value, which does not beat
# it, and the credited cylinder writes the solution at the end.
if self.spcomm is not None and \
getattr(self.spcomm, "communicators", None):
spoke_bounds = None
if self.cylinder_rank == 0:
spoke_bounds = checkpointing.spoke_inner_bounds_to_restore(
self.spcomm.communicators, self.options["resume_from"])
# A spoke resuming in place may replace its file while the
# hub's ranks read it, and hub ranks that disagreed on the
# inner bound could disagree on when to stop.
spoke_bounds = self.mpicomm.bcast(spoke_bounds, root=0)
comm = self.spcomm
for strata_rank, bound in spoke_bounds:
comm.BestInnerBound = comm.InnerBoundUpdate(
bound, comm.communicators[strata_rank]["spcomm_class"],
strata_rank)
# Without this the incumbent objective reads as None, which
# update_best_solution_if_improving treats as "accept anything" --
# so the first xhat after a resume, however bad, would replace the
# checkpointed best solution.
restored_incumbent = \
self._checkpoint_leaf_state["best_solution_obj_val"]
if restored_incumbent is not None:
self.best_solution_obj_val = restored_incumbent
elif self._iter0_solved_with_prox:
# The prox term makes these objective values no bound at all.
self.trivial_bound = None
global_toc("Iteration 0 was solved with the prox term on (xbar "
"was supplied), so it gives no trivial bound",
self.cylinder_rank == 0)
else:
self.trivial_bound = self.Ebound(verbose)
if self.trivial_bound is not None and self._can_update_best_bound():
self.best_bound_obj_val = self.trivial_bound
if hasattr(self.spcomm, "sync_nonants"):
self.spcomm.sync_nonants()
self.spcomm.sync_extensions()
elif hasattr(self.spcomm, "sync"):
self.spcomm.sync()
if have_extensions:
self.extobject.post_iter0_after_sync()
# On a resume, rho rides in the reloaded model -- including whatever a
# rho updater had done to it by the time of the checkpoint -- so
# re-running the setter would silently undo that.
if self.rho_setter is not None and not self._resumed_from_checkpoint:
if self.cylinder_rank == 0:
self._use_rho_setter(verbose)
else:
self._use_rho_setter(False)
if not self._resumed_from_checkpoint:
set_derived_surrogate_rhos(self)
# Central enforcement of rho > 0 once all initial rho-setting is done
# (defaults, post_iter0 rho extensions, and any rho_setter); see issue #560.
check_rhos_positive(self, source="after Iter0 rho setup")
## If ratio: Add reset p according to rho
# Skipped on a resume for the same reason as the rho_setter above: the
# reloaded model already carries the scaled p, and rescaling would
# compound it by a further factor of rho on every resume.
if smooth_type == 2 and not self._resumed_from_checkpoint:
for _, scenario in self.local_scenarios.items():
for ndn_i, _ in scenario._mpisppy_data.nonant_indices.items():
scenario._mpisppy_model.p[ndn_i] *= scenario._mpisppy_model.rho[ndn_i]
if have_converger:
# Call the constructor of the converger object
self.convobject = self.ph_converger(self)
#global_toc('Rank: {} - Before iter loop'.format(self.cylinder_rank), True)
self.conv = None
if dprogress and self.cylinder_rank == 0:
print("")
print("After PH Iteration",self._PHIter)
print("Trivial bound =", self.trivial_bound)
print("PHBase Convergence Metric =",self.conv)
print("Elapsed time: %6.2f" % (time.perf_counter() - self.start_time))
if dconvergence_detail:
self.report_var_values_at_rank0(header="Convergence detail:", fixed_vars=False)
# Unless the terms were attached already (in PH_Prep, or before the
# iteration-0 solve at an extension's request), iteration 0 solved
# the user's original objective. Now splice the dual (W) and
# proximal terms into the subproblem objectives. Deferring to here
# keeps the iteration-0 model structurally identical to what the user
# passed in -- helpful for debugging and for LP-only solvers that
# cannot handle the quadratic prox term until iteration 1.
if getattr(self, "_deferred_ph_attach", False):
self._attach_PH_to_objective_after_iter0()
self.reenable_W_and_prox()
# Last thing in Iter0, because everything an extension or converger
# rebuilds from the models on the way through has now run and would
# otherwise overwrite what is restored here.
self._restore_extension_state_if_resuming()
# Clear the dynamic-overrides overlay at the iter0→iterk
# transition: static iterk options come from the layer fold,
# and dropping any Gapper auto-mode mipgap accumulated during
# iter0 lets iterk start from the static fold + fresh updates.
self.current_solver_options = {}
return self.trivial_bound
[docs]
def iterk_loop(self):
""" Perform all PH iterations after iteration 0.
This function terminates if any of the following occur:
1. The maximum number of iterations is reached.
2. The user specifies a converger, and the `is_converged()` method of
that converger returns True.
3. The hub tells it to terminate.
4. The user does not specify a converger, and the default convergence
criteria are met (i.e. the convergence value falls below the
user-specified threshold).
Args: None
"""
verbose = self.options["verbose"]
have_extensions = self.extensions is not None
have_converger = self.ph_converger is not None
dprogress = self.options["display_progress"]
dtiming = self.options["display_timing"]
dconvergence_detail = self.options["display_convergence_detail"]
smoothed = bool(self.options["smoothed"])
self.conv = None
max_iterations = int(self.options["PHIterLimit"])
if hasattr(self.spcomm, "is_converged"):
# print a screen trace for iteration 0
if self.spcomm.is_converged():
global_toc("Cylinder convergence", self.cylinder_rank == 0)
return
# _PHIter is the *global* iteration number: on a resume it picks up
# where the checkpoint left off, so checkpoint generations do not
# collide with the pre-stop ones. The two bounds are counted
# differently on purpose. PHIterLimit (--max-iterations) bounds this
# run, so resuming with 2 does two more iterations whatever number the
# checkpoint stopped at, while stop_at_iteration_number bounds the
# whole study as an absolute iteration number. Whichever arrives first
# ends the run.
self._stop_iteration = self._resume_iteration + max_iterations
stop_at = self.options.get("stop_at_iteration_number", None)
if stop_at is not None:
stop_at = int(stop_at)
self._stop_iteration = min(self._stop_iteration, stop_at)
if stop_at <= self._resume_iteration:
# The loop below is simply empty in this case. Announcing it
# is what keeps a finished study from looking like a run that
# started up, did nothing and gave no reason.
global_toc(f"Nothing to do: --stop-at-iteration-number "
f"{stop_at} was already reached at iteration "
f"{self._resume_iteration}",
self.cylinder_rank == 0)
cycle_mark = time.perf_counter()
for self._PHIter in range(self._resume_iteration + 1,
self._stop_iteration + 1):
iteration_start_time = time.perf_counter()
if dprogress:
global_toc(f"Initiating PH Iteration {self._PHIter}\n", self.cylinder_rank == 0)
# Compute xbar
#global_toc('Rank: {} - Before Compute_Xbar'.format(self.cylinder_rank), True)
self.Compute_Xbar(verbose)
#global_toc('Rank: {} - After Compute_Xbar'.format(self.cylinder_rank), True)
# update the weights
self.Update_W(verbose)
#global_toc('Rank: {} - After Update_W'.format(self.cylinder_rank), True)
if hasattr(self.spcomm, "sync_Ws"):
self.spcomm.sync_Ws()
if smoothed:
self.Update_z(verbose)
self.conv = self.convergence_diff()
#global_toc('Rank: {} - After convergence_diff'.format(self.cylinder_rank), True)
if have_extensions:
self.extobject.miditer()
# Extensions may update ordinary rhos in miditer. Derived
# surrogate rhos are always the final rho transformation before
# the next PH solve.
set_derived_surrogate_rhos(self)
# The hub object takes precedence
# over the converger, such that
# the spokes will always have the
# latest data, even at termination
if have_converger:
if self.convobject.is_converged():
global_toc("User-supplied converger determined termination criterion reached", self.cylinder_rank == 0)
break
if self.conv is not None:
if self.conv < self.options["convthresh"]:
global_toc(f'Convergence metric={self.conv:f} dropped below user-supplied threshold={self.options["convthresh"]:f}', self.cylinder_rank == 0)
break
if (self.options.get("time_limit", None) is not None
or self._slurm_deadline is not None):
local_stop_reason = self._local_time_limit_stop_reason()
time_to_stop = self.allreduce_or(local_stop_reason is not None)
if time_to_stop:
global_toc(
local_stop_reason
or "Soft time limit reached on another rank.",
self.cylinder_rank == 0,
)
break
# Enforce rho > 0 before every solve: any rho-updating extension may
# have changed rho this iteration, so this is the single consistent
# place to catch a non-positive value before it reaches the solver
# (see issue #560).
check_rhos_positive(self, source=f"PH iteration {self._PHIter}")
teeme = (
"tee-rank0-solves" in self.options
and self.options["tee-rank0-solves"]
and self.cylinder_rank == 0
)
# Before the first proximal (quadratic) solve of this process,
# fail fast with guidance if the solver reports it cannot handle
# a quadratic objective; see issue #762. The gate is the first
# iteration of this leg rather than iteration 1: a resumed run
# starts past 1 and may legitimately have switched solvers.
if self._first_prox_solve():
self._check_prox_solver_capability()
try:
self.solve_loop(
solver_options=self._effective_solver_options(self._PHIter),
dtiming=dtiming,
gripe=True,
disable_pyomo_signal_handling=False,
tee=teeme,
verbose=verbose,
warmstart=True,
)
except Exception as e:
# Some solvers reject a quadratic objective by *raising* during
# the solve rather than returning no solution -- e.g. cbc/glpk,
# whose LP writer raises before the reactive check below can
# run. If this is the first quadratic solve, re-raise with an
# actionable message; see issue #762.
self._reraise_as_prox_capability_error(e)
raise
# If the first proximal solve produced nothing, the solver may not
# support quadratic objectives; give an actionable message
# (see issue #762).
self._check_prox_solve_succeeded()
# Predict --checkpoint-before-seconds from the time between
# completed solves; the first interval starts at loop entry.
now = time.perf_counter()
self._last_iteration_seconds = now - cycle_mark
cycle_mark = now
if have_extensions:
self.extobject.enditer()
if hasattr(self.spcomm, "sync_nonants"):
self.spcomm.sync_nonants()
self.spcomm.sync_bounds()
self.spcomm.sync_extensions()
elif hasattr(self.spcomm, "sync"):
self.spcomm.sync()
# Include synchronized bounds and extension state in the snapshot.
cylinder_converged = bool(
self.spcomm and self.spcomm.is_converged())
# Preserve this hook's existing skip on convergence.
if have_extensions and not cylinder_converged:
self.extobject.enditer_after_sync()
# Apply the usual checkpoint schedule before either exit path.
if have_extensions:
self.extobject.maybe_checkpoint()
if cylinder_converged:
global_toc("Cylinder convergence", self.cylinder_rank == 0)
break
if dprogress and self.cylinder_rank == 0:
print("")
print("After PH Iteration",self._PHIter)
print("Scaled PHBase Convergence Metric=",self.conv)
print("Iteration time: %6.2f" % (time.perf_counter() - iteration_start_time))
print("Elapsed time: %6.2f" % (time.perf_counter() - self.start_time))
if dconvergence_detail:
self.report_var_values_at_rank0(header="Convergence detail:", fixed_vars=False)
else: # no break, (self._PHIter == self._stop_iteration)
# NOTE: If we return for any other reason things are reasonably in-sync.
# due to the convergence check. However, here we return we'll be
# out-of-sync because of the solve_loop could take vasty different
# times on different threads. This can especially mess up finalization.
# As a guard, we'll put a barrier here.
self.mpicomm.Barrier()
# Name the bound that actually ended the run: on a resume the two
# are different numbers, and reporting the wrong one sends the
# reader looking for the wrong option.
if self._stop_iteration <= self._resume_iteration:
# The loop was empty. Its reason was reported before it, and
# announcing a bound as "reached" here would be a second,
# contradictory account of the same non-event.
pass
elif stop_at is not None and self._stop_iteration == stop_at:
global_toc(f"Reached user-specified stop_at_iteration_number={stop_at}, "
"ending the study", self.cylinder_rank == 0)
else:
global_toc(f"Reached user-specified limit={max_iterations} on number of PH iterations", self.cylinder_rank == 0)
[docs]
def post_loops(self, extensions=None):
""" Call scenario denouement methods, and report the expected objective
value.
Args:
extensions (object, optional):
PH extension object.
Returns:
float:
Pretty useless weighted, proxed objective value.
"""
verbose = self.options["verbose"]
have_extensions = extensions is not None
dprogress = self.options["display_progress"]
dtiming = self.options["display_timing"]
# for reporting sanity
self.mpicomm.Barrier()
if self.cylinder_rank == 0 and dprogress:
print("")
print("Invoking scenario reporting functions, if applicable")
print("")
if self.scenario_denouement is not None:
for sname,s in self.local_scenarios.items():
self.scenario_denouement(self.cylinder_rank, sname, s)
self.mpicomm.Barrier()
if self.cylinder_rank == 0 and dprogress:
print("")
print("Invoking PH extension finalization, if applicable")
print("")
if have_extensions:
self.extobject.post_everything()
if self.ph_converger is not None and hasattr(self.ph_converger, 'post_everything'):
self.convobject.post_everything()
Eobj = self.Eobjective(verbose)
self.mpicomm.Barrier()
if dprogress and self.cylinder_rank == 0:
print("")
print("Current ***weighted*** E[objective] =", Eobj)
print("")
if dtiming and self.cylinder_rank == 0:
print("")
print("Cumulative execution time=%5.2f" % (time.perf_counter()-self.start_time))
print("")
return Eobj
[docs]
def attach_xbars(self):
""" Attach xbar and xbar^2 Pyomo parameters to each model in
`local_scenarios`.
"""
for scenario in self.local_scenarios.values():
scenario._mpisppy_model.xbars = pyo.Param(
scenario._mpisppy_data.nonant_indices.keys(), initialize=0.0, mutable=True
)
scenario._mpisppy_model.xsqbars = pyo.Param(
scenario._mpisppy_data.nonant_indices.keys(), initialize=0.0, mutable=True
)
if __name__ == "__main__":
print ("No main for PHBase")