use super::*;
use super::asymptote_certificate::{
AsymptoteSample, AsymptoteSide, AsymptoteTolerances, AsymptoteVerdict, AsymptoteWindow,
MIN_TAIL_SAMPLES, assess_coordinate,
};
pub(crate) const OPERATOR_TRUST_RESTART_RADIUS_FLOOR: f64 = 1.0e-6;
#[derive(Clone, Debug)]
pub(crate) struct BoundInnerSeed {
pub(crate) theta: Array1<f64>,
pub(crate) beta: Array1<f64>,
}
pub(crate) fn outer_theta_bitwise_eq(left: &Array1<f64>, right: &Array1<f64>) -> bool {
left.len() == right.len()
&& left
.iter()
.zip(right.iter())
.all(|(left, right)| left.to_bits() == right.to_bits())
}
pub(crate) fn install_matching_initial_inner_seed(
obj: &mut dyn OuterObjective,
config: &OuterConfig,
seed: &Array1<f64>,
context: &str,
) -> Result<(), EstimationError> {
let Some(bound) = config.initial_inner_seed.as_ref() else {
return Ok(());
};
if !outer_theta_bitwise_eq(&bound.theta, seed) {
return Ok(());
}
match obj.seed_inner_state(&bound.beta)? {
SeedOutcome::Installed => log::info!(
"[CACHE] beta-warm context={} theta_dim={} beta_dim={} action=installed",
context,
bound.theta.len(),
bound.beta.len(),
),
SeedOutcome::NoSlot => log::warn!(
"[CACHE] beta-warm context={} theta_dim={} beta_dim={} action=skip \
reason=objective_has_no_inner_beta_slot",
context,
bound.theta.len(),
bound.beta.len(),
),
SeedOutcome::Incompatible => log::info!(
"[CACHE] beta-warm context={} theta_dim={} beta_dim={} action=rho-only \
reason=seed_beta_incompatible_with_inner_state",
context,
bound.theta.len(),
bound.beta.len(),
),
}
Ok(())
}
pub(crate) struct TerminalInnerCapGuard<'a> {
cap: &'a AtomicUsize,
previous: usize,
}
impl<'a> TerminalInnerCapGuard<'a> {
pub(crate) fn lift(feedback: &'a InnerProgressFeedback) -> Self {
let cap = feedback.cap.as_ref();
let previous = cap.swap(0, Ordering::Relaxed);
Self { cap, previous }
}
}
impl Drop for TerminalInnerCapGuard<'_> {
fn drop(&mut self) {
self.cap.store(self.previous, Ordering::Relaxed);
}
}
#[derive(Clone, Debug)]
pub(crate) struct OuterConfig {
pub(crate) tolerance: f64,
pub(crate) rel_cost_tolerance: Option<f64>,
pub(crate) max_iter: usize,
pub(crate) bounds: Option<(Array1<f64>, Array1<f64>)>,
pub(crate) seed_config: gam_problem::SeedConfig,
pub(crate) rho_bound: f64,
pub(crate) heuristic_lambdas: Option<Vec<f64>>,
pub(crate) initial_rho: Option<Array1<f64>>,
pub(crate) initial_inner_seed: Option<BoundInnerSeed>,
pub(crate) fallback_policy: FallbackPolicy,
pub(crate) screening_cap: Option<Arc<AtomicUsize>>,
pub(crate) screen_initial_rho: bool,
pub(crate) outer_inner_cap: Option<InnerProgressFeedback>,
pub(crate) operator_initial_trust_radius: Option<f64>,
pub(crate) arc_initial_regularization: Option<f64>,
pub(crate) objective_scale: Option<f64>,
pub(crate) bfgs_step_cap: Option<f64>,
pub(crate) bfgs_step_cap_psi: Option<f64>,
pub(crate) cache_session: Option<Arc<CacheSession>>,
pub(crate) cache_mirror_sessions: Vec<Arc<CacheSession>>,
pub(crate) rho_uncertainty_problem_size: crate::rho_uncertainty::RhoUncertaintyProblemSize,
pub(crate) warm_start_outer_hessian: Option<Array2<f64>>,
pub(crate) rho_canonical_keys: Option<Vec<u64>>,
}
impl Default for OuterConfig {
fn default() -> Self {
Self {
tolerance: 1e-5,
rel_cost_tolerance: None,
max_iter: 200,
bounds: None,
seed_config: gam_problem::SeedConfig::default(),
rho_bound: 30.0,
heuristic_lambdas: None,
initial_rho: None,
initial_inner_seed: None,
fallback_policy: FallbackPolicy::Automatic,
screening_cap: None,
screen_initial_rho: false,
outer_inner_cap: None,
operator_initial_trust_radius: None,
arc_initial_regularization: None,
objective_scale: None,
bfgs_step_cap: None,
bfgs_step_cap_psi: None,
cache_session: None,
cache_mirror_sessions: Vec::new(),
rho_uncertainty_problem_size:
crate::rho_uncertainty::RhoUncertaintyProblemSize::default(),
warm_start_outer_hessian: None,
rho_canonical_keys: None,
}
}
}
pub struct OuterProblem {
n_params: usize,
gradient: Derivative,
hessian: DeclaredHessianForm,
prefer_gradient_only: bool,
disable_fixed_point: bool,
psi_dim: usize,
barrier_config: Option<BarrierConfig>,
tolerance: f64,
rel_cost_tolerance: Option<f64>,
max_iter: usize,
bounds: Option<(Array1<f64>, Array1<f64>)>,
rho_bound: f64,
seed_config: gam_problem::SeedConfig,
heuristic_lambdas: Option<Vec<f64>>,
initial_rho: Option<Array1<f64>>,
fallback_policy: FallbackPolicy,
screening_cap: Option<Arc<AtomicUsize>>,
screen_initial_rho: bool,
outer_inner_cap: Option<InnerProgressFeedback>,
operator_initial_trust_radius: Option<f64>,
arc_initial_regularization: Option<f64>,
objective_scale: Option<f64>,
bfgs_step_cap: Option<f64>,
bfgs_step_cap_psi: Option<f64>,
cache_session: Option<Arc<CacheSession>>,
cache_mirror_sessions: Vec<Arc<CacheSession>>,
rho_uncertainty_problem_size: crate::rho_uncertainty::RhoUncertaintyProblemSize,
rho_canonical_keys: Option<Vec<u64>>,
}
impl OuterProblem {
pub fn new(n_params: usize) -> Self {
Self {
n_params,
gradient: Derivative::Unavailable,
hessian: DeclaredHessianForm::Unavailable,
prefer_gradient_only: false,
disable_fixed_point: false,
psi_dim: 0,
barrier_config: None,
tolerance: 1e-5,
rel_cost_tolerance: None,
max_iter: 200,
bounds: None,
rho_bound: 30.0,
seed_config: gam_problem::SeedConfig::default(),
heuristic_lambdas: None,
initial_rho: None,
fallback_policy: FallbackPolicy::Automatic,
screening_cap: None,
screen_initial_rho: false,
outer_inner_cap: None,
operator_initial_trust_radius: None,
arc_initial_regularization: None,
objective_scale: None,
bfgs_step_cap: None,
bfgs_step_cap_psi: None,
cache_session: None,
cache_mirror_sessions: Vec::new(),
rho_uncertainty_problem_size:
crate::rho_uncertainty::RhoUncertaintyProblemSize::default(),
rho_canonical_keys: None,
}
}
pub fn with_rho_canonical_keys(mut self, keys: Option<Vec<u64>>) -> Self {
self.rho_canonical_keys = keys;
self
}
pub fn with_gradient(mut self, d: Derivative) -> Self {
self.gradient = d;
self
}
pub fn with_hessian(mut self, form: DeclaredHessianForm) -> Self {
self.hessian = form;
self
}
pub fn with_prefer_gradient_only(mut self, prefer_gradient_only: bool) -> Self {
self.prefer_gradient_only = prefer_gradient_only;
self
}
pub fn with_disable_fixed_point(mut self, disable: bool) -> Self {
self.disable_fixed_point = disable;
self
}
pub fn with_psi_dim(mut self, dim: usize) -> Self {
self.psi_dim = dim;
self
}
pub fn with_barrier(mut self, cfg: Option<BarrierConfig>) -> Self {
self.barrier_config = cfg;
self
}
pub fn with_tolerance(mut self, tol: f64) -> Self {
self.tolerance = tol;
self
}
pub fn with_max_iter(mut self, n: usize) -> Self {
self.max_iter = n;
self
}
pub fn with_bounds(mut self, lo: Array1<f64>, hi: Array1<f64>) -> Self {
self.bounds = Some((lo, hi));
self
}
pub fn with_rho_bound(mut self, b: f64) -> Self {
self.rho_bound = b;
self
}
pub fn with_seed_config(mut self, sc: gam_problem::SeedConfig) -> Self {
self.seed_config = sc;
self
}
pub fn with_heuristic_lambdas(mut self, h: Vec<f64>) -> Self {
self.heuristic_lambdas = Some(h);
self
}
pub fn with_initial_rho(mut self, rho: Array1<f64>) -> Self {
self.initial_rho = Some(rho);
self
}
pub fn with_screening_cap(mut self, screening_cap: Arc<AtomicUsize>) -> Self {
self.screening_cap = Some(screening_cap);
self
}
pub fn with_screen_initial_rho(mut self, screen_initial_rho: bool) -> Self {
self.screen_initial_rho = screen_initial_rho;
self
}
pub fn with_outer_inner_cap(mut self, feedback: InnerProgressFeedback) -> Self {
self.outer_inner_cap = Some(feedback);
self
}
pub fn with_stuck_stall_cold_reeval_signal(self, signal: Arc<AtomicBool>) -> Self {
self.with_outer_inner_cap(InnerProgressFeedback {
cap: Arc::new(AtomicUsize::new(0)),
accepted_iter: Arc::new(AtomicUsize::new(0)),
last_iters: Arc::new(AtomicUsize::new(0)),
last_converged: Arc::new(AtomicBool::new(true)),
ift_residual: Arc::new(AtomicU64::new(f64::NAN.to_bits())),
accept_rho: Arc::new(AtomicU64::new(f64::NAN.to_bits())),
force_cold: signal,
})
}
pub fn with_operator_initial_trust_radius(mut self, radius: Option<f64>) -> Self {
self.operator_initial_trust_radius = sanitized_operator_trust_restart_radius(radius);
self
}
pub fn with_arc_initial_regularization(mut self, sigma: Option<f64>) -> Self {
self.arc_initial_regularization = sigma.filter(|v| v.is_finite() && *v > 0.0);
self
}
pub fn with_objective_scale(mut self, scale: Option<f64>) -> Self {
self.objective_scale = scale.filter(|v| v.is_finite() && *v > 0.0);
self
}
pub fn with_rel_cost_tolerance(mut self, rel_cost: Option<f64>) -> Self {
self.rel_cost_tolerance = rel_cost.filter(|v| v.is_finite() && *v > 0.0);
self
}
pub fn with_bfgs_step_cap(mut self, cap: Option<f64>) -> Self {
self.bfgs_step_cap = cap.filter(|v| v.is_finite() && *v > 0.0);
self
}
pub fn with_bfgs_step_cap_psi(mut self, cap: Option<f64>) -> Self {
self.bfgs_step_cap_psi = cap.filter(|v| v.is_finite() && *v > 0.0);
self
}
pub fn with_cache_session(mut self, session: Arc<CacheSession>) -> Self {
self.cache_session = Some(session);
self
}
pub fn with_cache_mirror_sessions(mut self, sessions: Vec<Arc<CacheSession>>) -> Self {
self.cache_mirror_sessions = sessions;
self
}
pub fn with_problem_size(mut self, n_obs: usize, p_coefficients: usize) -> Self {
self.rho_uncertainty_problem_size = crate::rho_uncertainty::RhoUncertaintyProblemSize {
n_obs: Some(n_obs),
p_coefficients: Some(p_coefficients),
};
self
}
pub fn with_fallback_policy(mut self, policy: FallbackPolicy) -> Self {
self.fallback_policy = policy;
self
}
fn capability(&self) -> OuterCapability {
OuterCapability {
gradient: self.gradient,
hessian: self.hessian,
prefer_gradient_only: self.prefer_gradient_only,
disable_fixed_point: self.disable_fixed_point,
n_params: self.n_params,
psi_dim: self.psi_dim,
fixed_point_available: false,
barrier_config: self.barrier_config.clone(),
}
}
pub(crate) fn config(&self) -> OuterConfig {
OuterConfig {
tolerance: self.tolerance,
rel_cost_tolerance: self.rel_cost_tolerance,
max_iter: self.max_iter,
bounds: self.bounds.clone(),
seed_config: self.seed_config,
rho_bound: self.rho_bound,
heuristic_lambdas: self.heuristic_lambdas.clone(),
initial_rho: self.initial_rho.clone(),
initial_inner_seed: None,
fallback_policy: self.fallback_policy,
screening_cap: self.screening_cap.clone(),
screen_initial_rho: self.screen_initial_rho,
outer_inner_cap: self.outer_inner_cap.clone(),
operator_initial_trust_radius: self.operator_initial_trust_radius,
arc_initial_regularization: self.arc_initial_regularization,
objective_scale: self.objective_scale,
bfgs_step_cap: self.bfgs_step_cap,
bfgs_step_cap_psi: self.bfgs_step_cap_psi,
cache_session: self.cache_session.clone(),
cache_mirror_sessions: self.cache_mirror_sessions.clone(),
rho_uncertainty_problem_size: self.rho_uncertainty_problem_size,
warm_start_outer_hessian: None,
rho_canonical_keys: self.rho_canonical_keys.clone(),
}
}
pub fn build_objective<S, Fc, Fe, Fr, Fefs>(
&self,
state: S,
cost_fn: Fc,
eval_fn: Fe,
reset_fn: Option<Fr>,
efs_fn: Option<Fefs>,
) -> ClosureObjective<S, Fc, Fe, Fr, Fefs>
where
Fc: FnMut(&mut S, &Array1<f64>) -> Result<f64, EstimationError>,
Fe: FnMut(&mut S, &Array1<f64>) -> Result<OuterEval, EstimationError>,
Fr: FnMut(&mut S),
Fefs: FnMut(&mut S, &Array1<f64>) -> Result<EfsEval, EstimationError>,
{
let mut cap = self.capability();
cap.fixed_point_available = efs_fn.is_some();
ClosureObjective {
state,
cap,
cost_fn,
eval_fn,
eval_order_fn: None,
reset_fn,
efs_fn,
fixed_point_certificate_fn: None,
exact_polish_fn: None,
screening_proxy_fn: None::<fn(&mut S, &Array1<f64>) -> Result<f64, EstimationError>>,
seed_fn: None::<fn(&mut S, &Array1<f64>) -> Result<SeedOutcome, EstimationError>>,
terminal_eval_order: None,
}
}
pub fn build_objective_with_eval_order<S, Fc, Fe, Feo, Fr, Fefs>(
&self,
state: S,
cost_fn: Fc,
eval_fn: Fe,
eval_order_fn: Feo,
reset_fn: Option<Fr>,
efs_fn: Option<Fefs>,
) -> ClosureObjective<S, Fc, Fe, Fr, Fefs, Feo>
where
Fc: FnMut(&mut S, &Array1<f64>) -> Result<f64, EstimationError>,
Fe: FnMut(&mut S, &Array1<f64>) -> Result<OuterEval, EstimationError>,
Feo: FnMut(&mut S, &Array1<f64>, OuterEvalOrder) -> Result<OuterEval, EstimationError>,
Fr: FnMut(&mut S),
Fefs: FnMut(&mut S, &Array1<f64>) -> Result<EfsEval, EstimationError>,
{
let mut cap = self.capability();
cap.fixed_point_available = efs_fn.is_some();
ClosureObjective {
state,
cap,
cost_fn,
eval_fn,
eval_order_fn: Some(eval_order_fn),
reset_fn,
efs_fn,
fixed_point_certificate_fn: None,
exact_polish_fn: None,
screening_proxy_fn: None::<fn(&mut S, &Array1<f64>) -> Result<f64, EstimationError>>,
seed_fn: None::<fn(&mut S, &Array1<f64>) -> Result<SeedOutcome, EstimationError>>,
terminal_eval_order: None,
}
}
pub fn build_objective_with_screening_proxy<S, Fc, Fe, Feo, Fr, Fefs, Fsp>(
&self,
state: S,
cost_fn: Fc,
eval_fn: Fe,
eval_order_fn: Feo,
reset_fn: Option<Fr>,
efs_fn: Option<Fefs>,
screening_proxy_fn: Fsp,
) -> ClosureObjective<S, Fc, Fe, Fr, Fefs, Feo, Fsp>
where
Fc: FnMut(&mut S, &Array1<f64>) -> Result<f64, EstimationError>,
Fe: FnMut(&mut S, &Array1<f64>) -> Result<OuterEval, EstimationError>,
Feo: FnMut(&mut S, &Array1<f64>, OuterEvalOrder) -> Result<OuterEval, EstimationError>,
Fr: FnMut(&mut S),
Fefs: FnMut(&mut S, &Array1<f64>) -> Result<EfsEval, EstimationError>,
Fsp: FnMut(&mut S, &Array1<f64>) -> Result<f64, EstimationError>,
{
let mut cap = self.capability();
cap.fixed_point_available = efs_fn.is_some();
ClosureObjective {
state,
cap,
cost_fn,
eval_fn,
eval_order_fn: Some(eval_order_fn),
reset_fn,
efs_fn,
fixed_point_certificate_fn: None,
exact_polish_fn: None,
screening_proxy_fn: Some(screening_proxy_fn),
seed_fn: None::<fn(&mut S, &Array1<f64>) -> Result<SeedOutcome, EstimationError>>,
terminal_eval_order: None,
}
}
pub fn run(
&self,
obj: &mut dyn OuterObjective,
context: &str,
) -> Result<OuterResult, EstimationError> {
let mut config = self.config();
let objective_lower = obj.outer_domain_lower_bound()?;
let objective_upper = obj.outer_domain_upper_bound()?;
if objective_lower.is_some() || objective_upper.is_some() {
install_objective_domain(&mut config, self.n_params, objective_lower, objective_upper)?;
}
let Some(session) = config.cache_session.clone() else {
return run_outer(obj, &config, context);
};
let key_hex = session.key().to_hex();
let short_key = &key_hex[..8.min(key_hex.len())];
let mut had_hit = false;
let mut cached_inner_seed: Option<BoundInnerSeed> = None;
if let Some(loaded) = session.try_load_with_source() {
match classify_cache_entry_for_outer(&loaded, self.n_params) {
CacheSeedDecision::ExactFinal {
rho,
beta,
iterations,
prior_obj_display,
} => {
log::info!(
"[CACHE] final-hit key={}.. context={} rho_dim={} prior_obj={:.6e} iter={} action=resume-and-recertify",
short_key,
context,
rho.len(),
prior_obj_display,
iterations,
);
config.initial_rho = Some(rho.clone());
config.screen_initial_rho = false;
if !beta.is_empty() {
cached_inner_seed = Some(BoundInnerSeed {
theta: rho,
beta: Array1::from_vec(beta),
});
}
had_hit = true;
}
CacheSeedDecision::Seed {
rho,
beta,
hessian,
prior_obj_display,
iteration,
} => {
let beta_len = beta.len();
let beta_arr = if beta.is_empty() {
None
} else {
Some(Array1::from_vec(beta))
};
config.warm_start_outer_hessian = if self.hessian.is_analytic() {
hessian.and_then(|(dim, flat)| {
if dim == self.n_params && flat.len() == dim * dim {
Array2::from_shape_vec((dim, dim), flat).ok()
} else {
None
}
})
} else {
None
};
if config
.initial_rho
.as_ref()
.is_none_or(|initial| initial != rho)
{
log::info!(
"[CACHE] hit key={}.. context={} rho_dim={} beta_dim={} prior_obj={:.6e} iter={}",
short_key,
context,
rho.len(),
beta_len,
prior_obj_display,
iteration,
);
config.initial_rho = Some(rho.clone());
config.screen_initial_rho = false;
had_hit = true;
} else {
log::info!(
"[CACHE] hit key={}.. context={} rho_dim={} beta_dim={} already-aligned prior_obj={:.6e}",
short_key,
context,
rho.len(),
beta_len,
prior_obj_display,
);
had_hit = true;
}
if let Some(beta) = beta_arr {
cached_inner_seed = Some(BoundInnerSeed { theta: rho, beta });
}
}
CacheSeedDecision::Discard {
reason: "payload-shape-mismatch",
..
} => {
log::info!(
"[CACHE] skip key={}.. context={} reason=payload-shape-mismatch n_params={}",
short_key,
context,
self.n_params,
);
}
CacheSeedDecision::Discard {
reason,
prior_obj_display,
all_rho_finite,
} => {
log::info!(
"[CACHE] skip key={}.. context={} reason={} prior_obj={:.6e} all_rho_finite={}",
short_key,
context,
reason,
prior_obj_display,
all_rho_finite.unwrap_or(false),
);
}
}
} else {
log::info!(
"[CACHE] miss key={}.. context={} reason=fresh-fingerprint n_params={}",
short_key,
context,
self.n_params,
);
}
config.initial_inner_seed = cached_inner_seed;
let mut checkpointing = CheckpointingObjective::new(
obj,
Arc::clone(&session),
config.cache_mirror_sessions.clone(),
);
let result = run_outer(&mut checkpointing, &config, context);
let final_beta = checkpointing.last_inner_beta();
if let Ok(result) = result.as_ref()
&& result.final_value.is_finite()
&& result.converged
&& result
.criterion_certificate
.as_ref()
.is_some_and(OuterCriterionCertificate::certifies)
&& let Some(bytes) = encode_iterate(
&result.rho,
final_beta.as_ref(),
result.final_hessian.as_ref(),
result.final_value,
result.iterations as u64,
)
{
let saved = session.finalize(
&bytes,
Some(result.final_value),
Some(result.iterations as u64),
);
if saved {
log::info!(
"[CACHE] save key={}.. context={} final_obj={:.6e} iter={} resumed={}",
short_key,
context,
result.final_value,
result.iterations,
had_hit,
);
}
for mirror in &config.cache_mirror_sessions {
let mirror_saved = mirror.finalize(
&bytes,
Some(result.final_value),
Some(result.iterations as u64),
);
if mirror_saved {
let mirror_hex = mirror.key().to_hex();
log::info!(
"[CACHE] save key={}.. context={} mirror final_obj={:.6e} iter={}",
&mirror_hex[..8.min(mirror_hex.len())],
context,
result.final_value,
result.iterations,
);
}
}
}
result
}
pub fn run_certified(
&self,
obj: &mut dyn OuterObjective,
context: &str,
) -> Result<CertifiedOuterResult, EstimationError> {
let result = self.run(obj, context)?;
CertifiedOuterResult::from_optimizer_result(result).map_err(|reason| {
EstimationError::RemlOptimizationFailed(format!(
"{context}: outer result failed certified-fit validation: {reason}"
))
})
}
}
pub(crate) enum PlanRunOutcome {
Converged(OuterResult),
Exhausted(OuterResult),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OuterConvergedVia {
GradientStationary,
CriterionFlat {
residual_grad_norm: f64,
certificate_bound: f64,
},
FixedPointStationary {
projected_residual_inf_norm: f64,
certificate_bound: f64,
},
RecurrentIncumbent { consecutive_restores: usize },
AsymptoteStationary { rails: usize },
}
impl OuterConvergedVia {
pub fn as_str(&self) -> &'static str {
match self {
Self::GradientStationary => "converged_stationary",
Self::CriterionFlat { .. } => "converged_criterion_flat",
Self::FixedPointStationary { .. } => "converged_fixed_point",
Self::RecurrentIncumbent { .. } => "incumbent_stationary",
Self::AsymptoteStationary { .. } => "converged_asymptote_rail",
}
}
}
#[derive(Clone, Debug)]
pub struct OuterResult {
pub rho: Array1<f64>,
pub final_value: f64,
pub iterations: usize,
pub final_grad_norm: Option<f64>,
pub final_gradient: Option<Array1<f64>>,
pub final_hessian: Option<Array2<f64>>,
pub converged: bool,
pub plan_used: OuterPlan,
pub operator_trust_radius: Option<f64>,
pub operator_stop_reason: Option<OperatorTrustRegionStopReason>,
pub criterion_certificate: Option<OuterCriterionCertificate>,
pub converged_via: Option<OuterConvergedVia>,
pub flat_noise_grad_bound: Option<f64>,
pub rho_uncertainty_diagnostic: Option<crate::rho_uncertainty::RhoUncertaintyDiagnostic>,
pub tail_snap_reseed: Option<Array1<f64>>,
pub saddle_escape_reseed: Option<Array1<f64>>,
pub wrong_rail_reseed: Option<Array1<f64>>,
pub active_set_reseed: Option<ActiveSetReseed>,
}
#[derive(Clone, Debug)]
pub struct ActiveSetReseed {
pub rho: Array1<f64>,
pub bounds: (Array1<f64>, Array1<f64>),
pub frozen: Vec<usize>,
}
impl OuterResult {
pub fn new(
rho: Array1<f64>,
final_value: f64,
iterations: usize,
converged: bool,
plan_used: OuterPlan,
) -> Self {
Self {
rho,
final_value,
iterations,
final_grad_norm: None,
final_gradient: None,
final_hessian: None,
converged,
plan_used,
operator_trust_radius: None,
operator_stop_reason: None,
criterion_certificate: None,
converged_via: None,
flat_noise_grad_bound: None,
rho_uncertainty_diagnostic: None,
tail_snap_reseed: None,
saddle_escape_reseed: None,
wrong_rail_reseed: None,
active_set_reseed: None,
}
}
pub fn final_grad_norm_report(&self) -> String {
match self.final_grad_norm {
Some(g) => format!("{g:.3e}"),
None => "n/a".to_string(),
}
}
}
#[derive(Clone, Debug)]
pub struct CertifiedOuterResult {
result: OuterResult,
}
impl CertifiedOuterResult {
fn from_optimizer_result(result: OuterResult) -> Result<Self, String> {
if !result.converged {
return Err(format!(
"outer optimization did not converge after {} iterations",
result.iterations
));
}
if !result.final_value.is_finite() {
return Err(format!(
"outer optimization returned a non-finite objective: {}",
result.final_value
));
}
if result.rho.iter().any(|value| !value.is_finite()) {
return Err("outer optimization returned non-finite hyperparameters".to_string());
}
if result
.final_grad_norm
.is_some_and(|value| !value.is_finite() || value < 0.0)
{
return Err(format!(
"outer optimization returned an invalid gradient norm: {:?}",
result.final_grad_norm
));
}
let certificate = result
.criterion_certificate
.as_ref()
.ok_or_else(|| "outer optimization returned no analytic certificate".to_string())?;
if !certificate.certifies() {
return Err(format!(
"outer optimization certificate does not certify: {}",
certificate.summary()
));
}
if result.converged_via.is_none() {
return Err(
"outer optimization did not retain optimizer-owned termination provenance"
.to_string(),
);
}
Ok(Self { result })
}
pub fn rho(&self) -> &Array1<f64> {
&self.result.rho
}
pub fn iterations(&self) -> usize {
self.result.iterations
}
pub fn final_value(&self) -> f64 {
self.result.final_value
}
pub fn final_grad_norm(&self) -> Option<f64> {
self.result.final_grad_norm
}
pub fn final_gradient(&self) -> Option<&Array1<f64>> {
self.result.final_gradient.as_ref()
}
pub fn criterion_certificate(&self) -> &OuterCriterionCertificate {
self.result
.criterion_certificate
.as_ref()
.expect("CertifiedOuterResult always owns a validated certificate")
}
pub fn final_hessian(&self) -> Option<&Array2<f64>> {
self.result.final_hessian.as_ref()
}
}
#[cfg(test)]
mod certified_outer_result_tests {
use super::*;
#[test]
fn caller_boolean_and_zero_gradient_cannot_mint_outer_authority() {
let mut fabricated = OuterResult::new(
Array1::from_vec(vec![0.0]),
1.0,
3,
true,
OuterPlan {
solver: Solver::Bfgs,
hessian_source: HessianSource::BfgsApprox,
},
);
fabricated.final_grad_norm = Some(0.0);
fabricated.final_gradient = Some(Array1::from_vec(vec![0.0]));
fabricated.converged_via = Some(OuterConvergedVia::GradientStationary);
let reason = CertifiedOuterResult::from_optimizer_result(fabricated)
.expect_err("caller-written status and gradient must not mint a certificate");
assert!(reason.contains("no analytic certificate"), "{reason}");
}
}
#[derive(Debug)]
pub struct OuterStationaryPointRejection {
pub result: OuterResult,
pub source: EstimationError,
}
impl std::fmt::Display for OuterStationaryPointRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.source, f)
}
}
impl std::error::Error for OuterStationaryPointRejection {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.source)
}
}
pub fn audit_stationary_point(
obj: &mut dyn OuterObjective,
rho: Array1<f64>,
context: &str,
) -> Result<OuterResult, OuterStationaryPointRejection> {
let config = OuterConfig::default();
let selected_plan = plan(&obj.capability());
let mut result = OuterResult::new(rho, f64::INFINITY, 0, false, selected_plan);
match certify_outer_optimality(obj, &config, context, &mut result) {
Ok(certificate) => {
result.criterion_certificate = Some(certificate);
Ok(result)
}
Err(source) => Err(OuterStationaryPointRejection { result, source }),
}
}
pub(crate) fn certificate_hessian_is_psd(hessian: &Array2<f64>) -> Option<bool> {
let n = hessian.nrows();
if n == 0 || hessian.ncols() != n || hessian.iter().any(|v| !v.is_finite()) {
return None;
}
let max_diag = (0..n).fold(0.0_f64, |acc, j| acc.max(hessian[[j, j]].abs()));
let shift = f64::EPSILON.sqrt() * max_diag.max(1.0);
let mut chol = hessian.clone();
for j in 0..n {
chol[[j, j]] += shift;
}
for j in 0..n {
for k in 0..j {
let l_jk = chol[[j, k]];
for i in j..n {
chol[[i, j]] -= chol[[i, k]] * l_jk;
}
}
let pivot = chol[[j, j]];
if !(pivot > 0.0) || !pivot.is_finite() {
return Some(false);
}
let inv_sqrt = 1.0 / pivot.sqrt();
for i in j..n {
chol[[i, j]] *= inv_sqrt;
}
}
Some(true)
}
pub(crate) fn certificate_hessian_is_psd_off_railed(
hessian: &Array2<f64>,
railed: &[usize],
) -> Option<bool> {
if railed.is_empty() {
return certificate_hessian_is_psd(hessian);
}
let n = hessian.nrows();
let railed_set: std::collections::BTreeSet<usize> = railed.iter().copied().collect();
let interior: Vec<usize> = (0..n).filter(|k| !railed_set.contains(k)).collect();
if interior.is_empty() {
return Some(true);
}
let mut sub = Array2::<f64>::zeros((interior.len(), interior.len()));
for (i, &ri) in interior.iter().enumerate() {
for (j, &rj) in interior.iter().enumerate() {
sub[[i, j]] = hessian[[ri, rj]];
}
}
certificate_hessian_is_psd(&sub)
}
pub(crate) fn certificate_hessian_is_psd_off_railed_above_gradient_floor(
hessian: &Array2<f64>,
excluded: &[usize],
gradient: &Array1<f64>,
) -> Option<bool> {
let n = hessian.nrows();
if gradient.len() != n {
return certificate_hessian_is_psd_off_railed(hessian, excluded);
}
let mut floored = hessian.clone();
for k in 0..n {
floored[[k, k]] += gradient[k].abs();
}
certificate_hessian_is_psd_off_railed(&floored, excluded)
}
fn negative_curvature_escape_point(
obj: &mut dyn OuterObjective,
rho: &Array1<f64>,
gradient: &Array1<f64>,
hessian: &Array2<f64>,
railed: &[usize],
baseline_cost: f64,
bounds: &(Array1<f64>, Array1<f64>),
context: &str,
) -> Option<Array1<f64>> {
use faer::Side;
use gam_linalg::faer_ndarray::FaerEigh;
let n = hessian.nrows();
if n == 0 || hessian.ncols() != n || hessian.iter().any(|v| !v.is_finite()) {
return None;
}
let railed_set: std::collections::BTreeSet<usize> = railed.iter().copied().collect();
let interior: Vec<usize> = (0..n).filter(|k| !railed_set.contains(k)).collect();
if interior.is_empty() {
return None;
}
let m = interior.len();
let mut sub = Array2::<f64>::zeros((m, m));
for (i, &ri) in interior.iter().enumerate() {
for (j, &rj) in interior.iter().enumerate() {
sub[[i, j]] = hessian[[ri, rj]];
}
}
let (eigenvalues, eigenvectors) = match sub.eigh(Side::Lower) {
Ok(pair) => pair,
Err(err) => {
log::warn!(
"[CERTIFICATE] {context}: saddle-escape eigendecomposition failed ({err}); \
refusing at the checkpoint without a reseed"
);
return None;
}
};
let max_diag = interior
.iter()
.fold(0.0_f64, |acc, &j| acc.max(hessian[[j, j]].abs()));
let neg_margin = f64::EPSILON.sqrt() * max_diag.max(1.0);
let mut min_idx = 0usize;
for k in 1..eigenvalues.len() {
if eigenvalues[k] < eigenvalues[min_idx] {
min_idx = k;
}
}
if !(eigenvalues[min_idx] < -neg_margin) {
return None;
}
let v_sub = eigenvectors.column(min_idx);
let dir_norm = v_sub.dot(&v_sub).sqrt();
if !(dir_norm > 0.0) || !dir_norm.is_finite() {
return None;
}
let mut direction = Array1::<f64>::zeros(n);
for (i, &ri) in interior.iter().enumerate() {
direction[ri] = v_sub[i] / dir_norm;
}
let primary_sign = if gradient.dot(&direction) > 0.0 {
-1.0
} else {
1.0
};
const ESCAPE_STEP_SCALES: [f64; 5] = [1.0, 0.5, 0.25, 0.125, 0.0625];
let strict_floor = baseline_cost.abs().max(1.0) * (16.0 * f64::EPSILON);
let mut best: Option<(f64, Array1<f64>)> = None;
for sign in [primary_sign, -primary_sign] {
for &alpha in ESCAPE_STEP_SCALES.iter() {
let mut trial = rho.clone();
for i in 0..n {
trial[i] += sign * alpha * direction[i];
}
let trial = project_to_bounds(&trial, Some(bounds));
if outer_theta_bitwise_eq(&trial, rho) {
continue;
}
if let Ok(cost) = obj.eval_cost(&trial)
&& cost.is_finite()
&& cost < baseline_cost - strict_floor
&& best.as_ref().is_none_or(|(c, _)| cost < *c)
{
best = Some((cost, trial));
}
}
if best.is_some() {
break;
}
}
if let Err(err) = obj.eval_cost(rho) {
log::warn!(
"[CERTIFICATE] {context}: failed to restore the objective to the checkpoint \
after saddle-escape probing: {err}"
);
}
best.map(|(cost, point)| {
log::info!(
"[CERTIFICATE] {context}: interior strict saddle (λ_min={:.3e} < 0, |Pg| within \
band); minting a negative-curvature escape reseed (objective {:.6e} → {:.6e}) for \
one retry (#2357)",
eigenvalues[min_idx],
baseline_cost,
cost,
);
point
})
}
pub(crate) fn newton_predicted_decrease(hessian: &Array2<f64>, grad: &Array1<f64>) -> Option<f64> {
let n = hessian.nrows();
if n == 0 || hessian.ncols() != n || grad.len() != n {
return None;
}
if hessian.iter().any(|v| !v.is_finite()) || grad.iter().any(|v| !v.is_finite()) {
return None;
}
let max_diag = (0..n).fold(0.0_f64, |acc, j| acc.max(hessian[[j, j]].abs()));
let shift = f64::EPSILON.sqrt() * max_diag.max(1.0);
let mut l = hessian.clone();
for j in 0..n {
l[[j, j]] += shift;
}
for j in 0..n {
for k in 0..j {
let l_jk = l[[j, k]];
for i in j..n {
l[[i, j]] -= l[[i, k]] * l_jk;
}
}
let pivot = l[[j, j]];
if !(pivot > 0.0) || !pivot.is_finite() {
return None;
}
let inv_sqrt = 1.0 / pivot.sqrt();
for i in j..n {
l[[i, j]] *= inv_sqrt;
}
}
let mut y = grad.clone();
for j in 0..n {
let mut s = y[j];
for k in 0..j {
s -= l[[j, k]] * y[k];
}
y[j] = s / l[[j, j]];
}
let mut d = y;
for j in (0..n).rev() {
let mut s = d[j];
for k in (j + 1)..n {
s -= l[[k, j]] * d[k];
}
d[j] = s / l[[j, j]];
}
let quad = grad.dot(&d); if !quad.is_finite() || quad < 0.0 {
return None;
}
Some(0.5 * quad)
}
pub(crate) fn certificate_railed_lambdas(
rho: &Array1<f64>,
rho_dim: usize,
config: &OuterConfig,
) -> Vec<usize> {
(0..rho_dim.min(rho.len()))
.filter(|&k| {
let (lo, hi) = match config.bounds.as_ref() {
Some((lo, hi)) if k < lo.len() && k < hi.len() => (lo[k], hi[k]),
Some(_) => return false,
None => (-config.rho_bound, config.rho_bound),
};
(rho[k] - lo).abs() <= CERTIFICATE_RAIL_MARGIN
|| (hi - rho[k]).abs() <= CERTIFICATE_RAIL_MARGIN
})
.collect()
}
fn outer_nonconvergence_error(
context: &str,
reason: &str,
result: &OuterResult,
projected_grad_norm: Option<f64>,
stationarity_bound: f64,
) -> EstimationError {
EstimationError::RemlDidNotConverge {
context: context.to_string(),
reason: reason.to_string(),
iterations: result.iterations,
final_value: result.final_value,
projected_grad_norm,
stationarity_bound,
rho_checkpoint: result.rho.to_vec(),
}
}
fn certify_fixed_point_optimality(
obj: &mut dyn OuterObjective,
config: &OuterConfig,
context: &str,
result: &mut OuterResult,
) -> Result<OuterCriterionCertificate, EstimationError> {
let layout = obj.capability().theta_layout();
let evaluation = obj
.eval_fixed_point_certificate(&result.rho)
.map_err(|err| {
outer_nonconvergence_error(
context,
&format!("analytic fixed-point certificate evaluation failed: {err}"),
result,
None,
config.tolerance,
)
})?;
if !inner_solve_converged(config.outer_inner_cap.as_ref()) {
return Err(outer_nonconvergence_error(
context,
"terminal fixed-point evidence was evaluated at a non-converged inner state",
result,
None,
config.tolerance,
));
}
if evaluation.coordinates.len() != layout.n_params {
return Err(outer_nonconvergence_error(
context,
&format!(
"fixed-point certificate returned {} coordinates for an outer problem of dimension {}",
evaluation.coordinates.len(),
layout.n_params
),
result,
None,
config.tolerance,
));
}
if !evaluation.cost.is_finite() {
return Err(outer_nonconvergence_error(
context,
"fixed-point certificate returned a non-finite objective value",
result,
None,
config.tolerance,
));
}
let mut normalized_updates = Vec::with_capacity(layout.n_params);
let mut uncovered = Vec::new();
for (index, coordinate) in evaluation.coordinates.iter().enumerate() {
match coordinate {
FixedPointCoordinateCertificate::Covered { update, scale }
if update.is_finite() && scale.is_finite() && *scale > 0.0 =>
{
normalized_updates.push(*update / *scale);
}
FixedPointCoordinateCertificate::Covered { update, scale } => {
uncovered.push(format!(
"coordinate {index} has invalid covered residual update={update} scale={scale}"
));
normalized_updates.push(f64::NAN);
}
FixedPointCoordinateCertificate::Uncovered { reason } => {
uncovered.push(format!("coordinate {index}: {reason}"));
normalized_updates.push(f64::NAN);
}
}
}
if !uncovered.is_empty() {
return Err(outer_nonconvergence_error(
context,
&format!(
"fixed-point certificate lacks root-equivalent analytic coverage: {}",
uncovered.join("; ")
),
result,
None,
config.tolerance,
));
}
let (lower, upper) = outer_bounds_template(config, layout.n_params);
let mut raw_inf = 0.0_f64;
let mut projected_inf = 0.0_f64;
for index in 0..layout.n_params {
let update = normalized_updates[index];
raw_inf = raw_inf.max(update.abs());
let projected = if result.rho[index] <= lower[index] {
update.max(0.0)
} else {
update
};
let projected = if result.rho[index] >= upper[index] {
projected.min(0.0)
} else {
projected
};
projected_inf = projected_inf.max(projected.abs());
}
result.final_value = evaluation.cost;
result.final_grad_norm = None;
result.final_gradient = None;
result.final_hessian = None;
result.converged = false;
let certificate = OuterCriterionCertificate {
stationarity: OuterStationarityCertificate::FixedPoint {
residual_inf_norm: raw_inf,
projected_residual_inf_norm: projected_inf,
bound: config.tolerance,
covered_coordinates: layout.n_params,
},
hessian_psd: None,
lambdas_railed: certificate_railed_lambdas(&result.rho, layout.rho_dim(), config),
};
result.criterion_certificate = Some(certificate.clone());
if !certificate.certifies() {
return Err(outer_nonconvergence_error(
context,
&certificate.summary(),
result,
Some(projected_inf),
config.tolerance,
));
}
result.converged = true;
result.converged_via = match result.converged_via {
Some(via @ OuterConvergedVia::RecurrentIncumbent { .. }) => Some(via),
_ => Some(OuterConvergedVia::FixedPointStationary {
projected_residual_inf_norm: projected_inf,
certificate_bound: config.tolerance,
}),
};
log::info!("[CERTIFICATE] {context}: {}", certificate.summary());
Ok(certificate)
}
pub(crate) fn certify_outer_optimality(
obj: &mut dyn OuterObjective,
config: &OuterConfig,
context: &str,
result: &mut OuterResult,
) -> Result<OuterCriterionCertificate, EstimationError> {
let terminal_cap_guard = config
.outer_inner_cap
.as_ref()
.map(TerminalInnerCapGuard::lift);
if terminal_cap_guard.is_some() || obj.owns_terminal_coefficient_mode() {
obj.reset();
}
let outcome = certify_outer_optimality_at_terminal_fidelity(obj, config, context, result, true);
drop(terminal_cap_guard);
outcome
}
fn certify_outer_optimality_at_terminal_fidelity(
obj: &mut dyn OuterObjective,
config: &OuterConfig,
context: &str,
result: &mut OuterResult,
allow_tail_snap: bool,
) -> Result<OuterCriterionCertificate, EstimationError> {
let capability = obj.capability();
let layout = capability.theta_layout();
layout
.validate_point_len(&result.rho, "outer certificate point")
.map_err(|err| {
EstimationError::RemlOptimizationFailed(format!(
"{context}: invalid outer certificate point: {err}"
))
})?;
if result.rho.iter().any(|value| !value.is_finite()) {
return Err(outer_nonconvergence_error(
context,
"the selected checkpoint contains non-finite coordinates",
result,
None,
outer_gradient_tolerance(config).abs,
));
}
if layout.n_params == 0 {
let value = obj.eval_cost(&result.rho).map_err(|err| {
outer_nonconvergence_error(
context,
&format!("zero-dimensional final objective evaluation failed: {err}"),
result,
Some(0.0),
outer_gradient_tolerance(config).abs,
)
})?;
if !value.is_finite() {
return Err(outer_nonconvergence_error(
context,
"the zero-dimensional final objective is non-finite",
result,
Some(0.0),
outer_gradient_tolerance(config).abs,
));
}
let certificate = OuterCriterionCertificate {
stationarity: OuterStationarityCertificate::AnalyticGradient {
grad_norm: 0.0,
projected_grad_norm: 0.0,
bound: outer_gradient_tolerance(config).abs,
},
hessian_psd: None,
lambdas_railed: Vec::new(),
};
result.final_value = value;
result.final_grad_norm = Some(0.0);
result.final_gradient = Some(Array1::zeros(0));
result.final_hessian = None;
result.converged = true;
result.converged_via = Some(OuterConvergedVia::GradientStationary);
result.criterion_certificate = Some(certificate.clone());
return Ok(certificate);
}
if matches!(result.plan_used.solver, Solver::Efs | Solver::HybridEfs)
&& capability.gradient != Derivative::Analytic
{
return certify_fixed_point_optimality(obj, config, context, result);
}
if capability.gradient != Derivative::Analytic {
return Err(outer_nonconvergence_error(
context,
"the objective exposes no analytic gradient for final certification",
result,
None,
outer_gradient_tolerance(config).abs,
));
}
let order = if capability.hessian.is_analytic() {
OuterEvalOrder::ValueGradientHessian
} else {
OuterEvalOrder::ValueAndGradient
};
let evaluation = obj.eval_with_order(&result.rho, order).map_err(|err| {
outer_nonconvergence_error(
context,
&format!("analytic final-point evaluation failed: {err}"),
result,
result.final_grad_norm,
outer_gradient_tolerance(config).abs,
)
})?;
if !inner_solve_converged(config.outer_inner_cap.as_ref()) {
return Err(outer_nonconvergence_error(
context,
"terminal analytic evidence was evaluated at a non-converged inner state",
result,
None,
outer_gradient_tolerance(config).abs,
));
}
layout
.validate_gradient_len(&evaluation.gradient, "outer certificate gradient")
.map_err(|err| {
outer_nonconvergence_error(
context,
&format!("malformed analytic final gradient: {err}"),
result,
None,
outer_gradient_tolerance(config).abs,
)
})?;
if !evaluation.cost.is_finite() || evaluation.gradient.iter().any(|value| !value.is_finite()) {
return Err(outer_nonconvergence_error(
context,
"the analytic final-point value or gradient is non-finite",
result,
None,
outer_gradient_tolerance(config).abs,
));
}
let bounds = outer_bounds_template(config, layout.n_params);
let rail_projection_bounds = {
let (lower, upper) = &bounds;
(
lower.mapv(|v| v + CERTIFICATE_RAIL_MARGIN),
upper.mapv(|v| v - CERTIFICATE_RAIL_MARGIN),
)
};
let grad_norm = evaluation.gradient.dot(&evaluation.gradient).sqrt();
let terminal_beta = evaluation.inner_beta_hint.clone();
let projected_gradient = project_gradient_vector(
&result.rho,
&evaluation.gradient,
Some(&rail_projection_bounds),
);
let projected_grad_norm = projected_gradient.iter().map(|v| v * v).sum::<f64>().sqrt();
let solver_bound = outer_gradient_tolerance(config).threshold(evaluation.cost, grad_norm);
let mut stationarity_bound = if matches!(
result.operator_stop_reason,
Some(OperatorTrustRegionStopReason::CostStallFlatValley)
) {
solver_bound.max(flat_valley_converged_grad_bound(evaluation.cost))
} else {
solver_bound
};
if let Some(noise_bound) = result.flat_noise_grad_bound
&& noise_bound.is_finite()
{
stationarity_bound = stationarity_bound.max(noise_bound);
}
let run_recorded_gradient = result.final_gradient.take();
let run_recorded_value = result.final_value;
result.final_value = evaluation.cost;
result.final_grad_norm = Some(projected_grad_norm);
result.final_gradient = Some(evaluation.gradient);
result.converged = false;
let analytic_hessian = if capability.hessian.is_analytic() {
match evaluation.hessian.materialize_dense() {
Ok(Some(hessian)) => {
layout
.validate_hessian_shape(&hessian, "outer certificate Hessian")
.map_err(|err| {
outer_nonconvergence_error(
context,
&format!("malformed analytic final Hessian: {err}"),
result,
Some(projected_grad_norm),
stationarity_bound,
)
})?;
if hessian.iter().any(|value| !value.is_finite()) {
return Err(outer_nonconvergence_error(
context,
"the analytic final Hessian contains non-finite entries",
result,
Some(projected_grad_norm),
stationarity_bound,
));
}
Some(hessian)
}
Ok(None) => {
return Err(outer_nonconvergence_error(
context,
"the objective declared analytic curvature but returned none at the final point",
result,
Some(projected_grad_norm),
stationarity_bound,
));
}
Err(err) => {
return Err(outer_nonconvergence_error(
context,
&format!("analytic final Hessian could not be certified: {err}"),
result,
Some(projected_grad_norm),
stationarity_bound,
));
}
}
} else {
None
};
if let Some(hessian) = analytic_hessian.as_ref()
&& let Some(predicted_decrease) = newton_predicted_decrease(hessian, &projected_gradient)
&& predicted_decrease.is_finite()
&& predicted_decrease > 0.0
{
let objective_tol = outer_rel_cost_floor(config) * (1.0 + evaluation.cost.abs());
let curvature_grad_bound =
projected_grad_norm * (objective_tol / predicted_decrease).sqrt();
if curvature_grad_bound.is_finite() && curvature_grad_bound > stationarity_bound {
log::info!(
"[CERTIFICATE] {context}: curvature-scaled flat-valley bound {curvature_grad_bound:.3e} \
(|Pg|={projected_grad_norm:.3e}, Newton ½gᵀH⁻¹g={predicted_decrease:.3e} ≤ tol {objective_tol:.3e}) \
widened from gradient-band {stationarity_bound:.3e}"
);
stationarity_bound = curvature_grad_bound;
}
}
if projected_grad_norm > stationarity_bound
&& let Some(prior_gradient) = run_recorded_gradient.as_ref()
&& layout
.validate_gradient_len(prior_gradient, "outer run-recorded gradient")
.is_ok()
&& prior_gradient.iter().all(|value| value.is_finite())
&& run_recorded_value.is_finite()
{
const GRADIENT_REPRODUCIBILITY_WIDENING: f64 = 2.0;
let objective_tol = config
.rel_cost_tolerance
.unwrap_or(config.tolerance * 1.0e-2)
.max(COST_STALL_REL_TOL_FLOOR)
* (1.0 + evaluation.cost.abs());
let cost_drift = (run_recorded_value - evaluation.cost).abs();
let prior_projected =
project_gradient_vector(&result.rho, prior_gradient, Some(&rail_projection_bounds));
let spread = (&prior_projected - &projected_gradient)
.iter()
.map(|v| v * v)
.sum::<f64>()
.sqrt();
let repro_bound = GRADIENT_REPRODUCIBILITY_WIDENING * spread;
if cost_drift <= objective_tol
&& repro_bound.is_finite()
&& repro_bound > stationarity_bound
&& projected_grad_norm <= repro_bound
{
log::info!(
"[CERTIFICATE] {context}: gradient-reproducibility floor widened the \
stationarity bound to {repro_bound:.3e} (|Pg|={projected_grad_norm:.3e}, \
same-ρ spread between the run-recorded and certificate-time gradients \
{spread:.3e}, cost drift {cost_drift:.3e} ≤ tol {objective_tol:.3e})"
);
stationarity_bound = repro_bound;
}
}
let certificate_railed = certificate_railed_lambdas(&result.rho, layout.rho_dim(), config);
let asymptote_objective_tol = config
.rel_cost_tolerance
.unwrap_or(config.tolerance * 1.0e-2)
.max(COST_STALL_REL_TOL_FLOOR)
* (1.0 + evaluation.cost.abs());
let rail_outcome = match analytic_hessian.as_ref() {
Some(hessian) if !certificate_railed.is_empty() && grad_norm > stationarity_bound => {
Some(try_certify_asymptote_rail(
obj,
&AsymptoteRailInputs {
rho: &result.rho,
projected_gradient: &projected_gradient,
railed: &certificate_railed,
hessian,
bounds: &bounds,
terminal_beta: terminal_beta.as_ref(),
stationarity_bound,
objective_tol: asymptote_objective_tol,
context,
},
)?)
}
_ => None,
};
let mut asymptote_rail_note: Option<String> = None;
let mut probes_ran = rail_outcome.is_some();
if let Some(outcome) = rail_outcome {
match outcome {
Err(reason) => asymptote_rail_note = Some(reason),
Ok(minted) => {
let (interior_projected_grad_norm, effective_interior_bound, rails) = minted;
let restored = obj
.eval_with_order(&result.rho, OuterEvalOrder::ValueAndGradient)
.map_err(|err| {
EstimationError::RemlOptimizationFailed(format!(
"{context}: failed to re-own the certified point after \
asymptote-rail probing: {err}"
))
})?;
result.final_value = restored.cost;
let restored_projected = project_gradient_vector(
&result.rho,
&restored.gradient,
Some(&rail_projection_bounds),
);
result.final_grad_norm = Some(
restored_projected
.iter()
.map(|v| v * v)
.sum::<f64>()
.sqrt(),
);
result.final_gradient = Some(restored.gradient);
let certificate = OuterCriterionCertificate {
stationarity: OuterStationarityCertificate::AsymptoteRail {
interior_projected_grad_norm,
bound: effective_interior_bound,
rails,
},
hessian_psd: Some(true),
lambdas_railed: certificate_railed.clone(),
};
result.final_hessian = analytic_hessian;
result.criterion_certificate = Some(certificate.clone());
if !certificate.certifies() {
result.converged = false;
return Err(outer_nonconvergence_error(
context,
&certificate.summary(),
result,
Some(interior_projected_grad_norm),
stationarity_bound,
));
}
result.converged = true;
result.converged_via = Some(OuterConvergedVia::AsymptoteStationary {
rails: certificate.stationarity.rails().len(),
});
log::info!("[CERTIFICATE] {context}: {}", certificate.summary());
return Ok(certificate);
}
}
}
let mut certified_projected_grad_norm = projected_grad_norm;
if projected_grad_norm > stationarity_bound
&& let Some(hessian) = analytic_hessian.as_ref()
&& certificate_hessian_is_psd_off_railed(hessian, &certificate_railed) == Some(true)
{
let n = layout.n_params;
let max_diag = (0..n).fold(0.0_f64, |acc, j| acc.max(hessian[[j, j]].abs()));
let null_curvature_threshold = f64::EPSILON.sqrt() * max_diag.max(1.0);
let objective_tol = config
.rel_cost_tolerance
.unwrap_or(config.tolerance * 1.0e-2)
.max(COST_STALL_REL_TOL_FLOOR)
* (1.0 + evaluation.cost.abs());
const LARGE_STEP_DELTA: f64 = 1.0;
let mut saturated_flat: Vec<usize> = Vec::new();
let mut probe_reports: Vec<String> = Vec::new();
let mut probed_any = false;
let mut probe_failed = false;
for k in 0..n {
let row_inf = (0..n).fold(0.0_f64, |acc, j| acc.max(hessian[[k, j]].abs()));
if row_inf > null_curvature_threshold || projected_gradient[k] == 0.0 {
continue;
}
let mut plus = result.rho.clone();
plus[k] += LARGE_STEP_DELTA;
let mut minus = result.rho.clone();
minus[k] -= LARGE_STEP_DELTA;
probed_any = true;
let (Ok(cost_plus), Ok(cost_minus)) = (obj.eval_cost(&plus), obj.eval_cost(&minus))
else {
probe_failed = true;
break;
};
if !cost_plus.is_finite() || !cost_minus.is_finite() {
probe_failed = true;
break;
}
let up = (cost_plus - evaluation.cost).abs();
let down = (cost_minus - evaluation.cost).abs();
if up <= objective_tol && down <= objective_tol {
saturated_flat.push(k);
probe_reports.push(format!("k={k} |ΔV|+={up:.3e} |ΔV|-={down:.3e}"));
}
}
if !probe_failed && !saturated_flat.is_empty() {
let reduced_sq = (0..n)
.filter(|k| !saturated_flat.contains(k))
.map(|k| projected_gradient[k] * projected_gradient[k])
.sum::<f64>();
certified_projected_grad_norm = reduced_sq.sqrt();
let flat_list = saturated_flat
.iter()
.map(usize::to_string)
.collect::<Vec<_>>()
.join(", ");
let probe_summary = probe_reports.join("; ");
log::info!(
"[CERTIFICATE] {context}: large-step flatness certificate classified \
coordinate(s) [{flat_list}] saturated-flat (curvature row ≤ \
{null_curvature_threshold:.3e}, probed Δ=±{LARGE_STEP_DELTA} with \
{probe_summary}, cost-flat to tol {objective_tol:.3e}); projected \
gradient reduced from {projected_grad_norm:.3e} to \
{certified_projected_grad_norm:.3e}"
);
}
if probed_any {
obj.eval_cost(&result.rho).map_err(|err| {
outer_nonconvergence_error(
context,
&format!(
"failed to restore the objective to the certified point after \
flatness probing: {err}"
),
result,
Some(certified_projected_grad_norm),
stationarity_bound,
)
})?;
}
}
let certificate = OuterCriterionCertificate {
stationarity: OuterStationarityCertificate::AnalyticGradient {
grad_norm,
projected_grad_norm: certified_projected_grad_norm,
bound: stationarity_bound,
},
hessian_psd: analytic_hessian.as_ref().and_then(|hessian| {
certificate_hessian_is_psd_off_railed(hessian, &certificate_railed)
}),
lambdas_railed: certificate_railed.clone(),
};
let mut tail_snap_note: Option<String> = None;
if allow_tail_snap
&& !certificate.certifies()
&& grad_norm > stationarity_bound
&& let Some(hessian) = analytic_hessian.as_ref()
{
probes_ran = true;
match try_tail_snap_to_rail(
obj,
&AsymptoteRailInputs {
rho: &result.rho,
projected_gradient: &projected_gradient,
railed: &certificate_railed,
hessian,
bounds: &bounds,
terminal_beta: terminal_beta.as_ref(),
stationarity_bound,
objective_tol: asymptote_objective_tol,
context,
},
)? {
TailSnapOutcome::TailStationaryAtPoint {
rails,
interior_projected_grad_norm,
effective_interior_bound,
} => {
let restored = obj
.eval_with_order(&result.rho, OuterEvalOrder::ValueAndGradient)
.map_err(|err| {
EstimationError::RemlOptimizationFailed(format!(
"{context}: failed to re-own the certified point after \
tail-snap probing: {err}"
))
})?;
result.final_value = restored.cost;
let restored_projected = project_gradient_vector(
&result.rho,
&restored.gradient,
Some(&rail_projection_bounds),
);
result.final_grad_norm = Some(
restored_projected
.iter()
.map(|v| v * v)
.sum::<f64>()
.sqrt(),
);
result.final_gradient = Some(restored.gradient);
let certificate = OuterCriterionCertificate {
stationarity: OuterStationarityCertificate::AsymptoteRail {
interior_projected_grad_norm,
bound: effective_interior_bound,
rails,
},
hessian_psd: Some(true),
lambdas_railed: certificate_railed.clone(),
};
result.final_hessian = analytic_hessian;
result.criterion_certificate = Some(certificate.clone());
if !certificate.certifies() {
result.converged = false;
return Err(outer_nonconvergence_error(
context,
&certificate.summary(),
result,
Some(interior_projected_grad_norm),
effective_interior_bound,
));
}
result.converged = true;
result.converged_via = Some(OuterConvergedVia::AsymptoteStationary {
rails: certificate.stationarity.rails().len(),
});
log::info!(
"[CERTIFICATE] {context}: tail-stationary at the checkpoint \
(#2348 Inc 2c): {}",
certificate.summary()
);
return Ok(certificate);
}
TailSnapOutcome::Snapped(snapped) => {
let original_rho = result.rho.clone();
let saved_gradient = result.final_gradient.take();
result.final_value = f64::NAN;
log::info!(
"[CERTIFICATE] {context}: confirmed exponential tail on un-railed \
coordinate(s); snapping ρ {original_rho} → {snapped} and re-certifying \
at the rail (#2348 Inc 2)"
);
result.rho = snapped;
match certify_outer_optimality_at_terminal_fidelity(
obj, config, context, result, false,
) {
Ok(snap_certificate) => return Ok(snap_certificate),
Err(snap_err) => {
log::info!(
"[CERTIFICATE] {context}: snapped point refused \
({snap_err}); restoring the checkpoint and refusing at the \
original point"
);
tail_snap_note = Some(format!("snapped point refused: {snap_err}"));
result.rho = original_rho;
result.final_value = evaluation.cost;
result.final_grad_norm = Some(projected_grad_norm);
result.final_gradient = saved_gradient;
if let Err(restore_err) = obj.eval_cost(&result.rho) {
log::warn!(
"[CERTIFICATE] {context}: failed to restore the objective \
to the checkpoint after a refused tail snap: {restore_err}"
);
}
}
}
}
TailSnapOutcome::ConfirmedNeedsReseed(snapped) => {
log::info!(
"[CERTIFICATE] {context}: confirmed exponential tail on un-railed \
coordinate(s) but the interior is not yet stationary; publishing \
the snapped point {snapped} as a reseed for one retry (#2348 Inc 2b)"
);
tail_snap_note = Some(
"tail confirmed; interior unpolished — retry seeded at the snapped rail point"
.to_string(),
);
result.tail_snap_reseed = Some(snapped);
}
TailSnapOutcome::Declined(reason) => {
tail_snap_note = Some(reason);
}
}
}
result.final_hessian = analytic_hessian;
result.criterion_certificate = Some(certificate.clone());
if !certificate.certifies() {
result.converged = false;
result.wrong_rail_reseed = None;
result.active_set_reseed = None;
if allow_tail_snap
&& certificate.is_stationary()
&& !certificate.curvature_admissible()
&& let Some(hessian) = result.final_hessian.clone()
&& let Some(gradient) = result.final_gradient.clone()
{
let saddle_rho = result.rho.clone();
let baseline_cost = result.final_value;
result.saddle_escape_reseed = negative_curvature_escape_point(
obj,
&saddle_rho,
&gradient,
&hessian,
&certificate.lambdas_railed,
baseline_cost,
&bounds,
context,
);
}
if allow_tail_snap
&& !certificate_railed.is_empty()
&& let Some(hessian) = result.final_hessian.clone()
{
let beta_norm = terminal_beta
.as_ref()
.map(|b| b.dot(b).sqrt())
.filter(|v| v.is_finite())
.unwrap_or(0.0);
let mut rail_tol =
AsymptoteTolerances::exp4_rail_bands(ASYMPTOTE_ESTIMAND_REL_TOL * (1.0 + beta_norm));
rail_tol.tail_drift_rel = TAIL_SNAP_DRIFT_REL;
let (lower, upper) = &bounds;
let mut wrong_rail_point: Option<Array1<f64>> = None;
for &k in certificate_railed.iter() {
if k >= result.rho.len() || k >= lower.len() || k >= upper.len() {
continue;
}
let side = if (upper[k] - result.rho[k]).abs() <= (result.rho[k] - lower[k]).abs() {
AsymptoteSide::Upper
} else {
AsymptoteSide::Lower
};
if let Some(target) = detect_wrong_rail_pullback(
obj,
&result.rho,
k,
side,
&rail_tol,
(lower[k], upper[k]),
)? {
let mut reseed = result.rho.clone();
reseed[k] = target;
wrong_rail_point = Some(reseed);
break;
}
}
if let Some(reseed) = wrong_rail_point {
result.wrong_rail_reseed = Some(reseed);
} else {
let interior_indices: Vec<usize> = (0..projected_gradient.len())
.filter(|k| !certificate_railed.contains(k))
.collect();
let interior_not_stationary = !interior_indices.is_empty()
&& certify_interior_stationarity(
&projected_gradient,
&hessian,
&interior_indices,
stationarity_bound,
asymptote_objective_tol,
)
.is_err();
if interior_not_stationary {
let mut froz_lower = lower.clone();
let mut froz_upper = upper.clone();
let mut reseed = result.rho.clone();
let mut frozen: Vec<usize> = Vec::new();
for &k in certificate_railed.iter() {
if k >= reseed.len() {
continue;
}
let rail = if (upper[k] - reseed[k]).abs() <= (reseed[k] - lower[k]).abs() {
upper[k]
} else {
lower[k]
};
reseed[k] = rail;
froz_lower[k] = rail;
froz_upper[k] = rail;
frozen.push(k);
}
if !frozen.is_empty() {
result.active_set_reseed = Some(ActiveSetReseed {
rho: reseed,
bounds: (froz_lower, froz_upper),
frozen,
});
}
}
}
}
let mut summary = certificate.summary();
if let Some(note) = asymptote_rail_note {
summary = format!("{summary}; asymptote-rail declined: {note}");
}
let summary = match tail_snap_note {
Some(note) => format!("{summary}; tail-snap declined: {note}"),
None => summary,
};
return Err(outer_nonconvergence_error(
context,
&summary,
result,
Some(certified_projected_grad_norm),
stationarity_bound,
));
}
if probes_ran {
let restored = obj
.eval_with_order(&result.rho, OuterEvalOrder::ValueAndGradient)
.map_err(|err| {
EstimationError::RemlOptimizationFailed(format!(
"{context}: failed to re-own the certified point after rail/tail probing: {err}"
))
})?;
result.final_value = restored.cost;
let restored_projected = project_gradient_vector(
&result.rho,
&restored.gradient,
Some(&rail_projection_bounds),
);
result.final_grad_norm = Some(
restored_projected
.iter()
.map(|v| v * v)
.sum::<f64>()
.sqrt(),
);
result.final_gradient = Some(restored.gradient);
}
result.converged = true;
result.converged_via = match result.converged_via {
Some(via @ OuterConvergedVia::RecurrentIncumbent { .. }) => Some(via),
_ if certified_projected_grad_norm <= solver_bound => {
Some(OuterConvergedVia::GradientStationary)
}
_ => Some(OuterConvergedVia::CriterionFlat {
residual_grad_norm: certified_projected_grad_norm,
certificate_bound: stationarity_bound,
}),
};
log::info!("[CERTIFICATE] {context}: {}", certificate.summary());
Ok(certificate)
}
const ASYMPTOTE_ESTIMAND_REL_TOL: f64 = 1.0e-4;
const ASYMPTOTE_PROBE_COUNT: usize = 18;
struct AsymptoteRailInputs<'a> {
rho: &'a Array1<f64>,
projected_gradient: &'a Array1<f64>,
railed: &'a [usize],
hessian: &'a Array2<f64>,
bounds: &'a (Array1<f64>, Array1<f64>),
terminal_beta: Option<&'a Array1<f64>>,
stationarity_bound: f64,
objective_tol: f64,
context: &'a str,
}
fn try_certify_asymptote_rail(
obj: &mut dyn OuterObjective,
inputs: &AsymptoteRailInputs<'_>,
) -> Result<Result<(f64, f64, Vec<RailCoordinate>), String>, EstimationError> {
let rho = inputs.rho;
let projected_gradient = inputs.projected_gradient;
let railed = inputs.railed;
let interior_indices: Vec<usize> = (0..projected_gradient.len())
.filter(|k| !railed.contains(k))
.collect();
let (interior_projected_grad_norm, effective_interior_bound) =
match certify_interior_stationarity(
projected_gradient,
inputs.hessian,
&interior_indices,
inputs.stationarity_bound,
inputs.objective_tol,
) {
Ok(certified) => certified,
Err(reason) => return Ok(Err(reason)),
};
if certificate_hessian_is_psd_off_railed_above_gradient_floor(
inputs.hessian,
railed,
projected_gradient,
) != Some(true)
{
return Ok(Err("interior Hessian sub-block is not PSD".to_string()));
}
let beta_norm = inputs
.terminal_beta
.map(|b| b.dot(b).sqrt())
.filter(|v| v.is_finite())
.unwrap_or(0.0);
let estimand_tol = ASYMPTOTE_ESTIMAND_REL_TOL * (1.0 + beta_norm);
let mut tol = AsymptoteTolerances::exp4_rail_bands(estimand_tol);
tol.tail_drift_rel = TAIL_SNAP_DRIFT_REL;
let (lower, upper) = inputs.bounds;
let mut rails: Vec<RailCoordinate> = Vec::new();
let mut decline: Option<String> = None;
let mut probed_any = false;
for &k in railed.iter() {
if k >= rho.len() || k >= lower.len() || k >= upper.len() {
decline = Some(format!("railed coordinate {k} outside the box layout"));
break;
}
let side = if (upper[k] - rho[k]).abs() <= (rho[k] - lower[k]).abs() {
AsymptoteSide::Upper
} else {
AsymptoteSide::Lower
};
probed_any = true;
match build_and_assess_rail_coordinate(obj, rho, k, side, &tol, (lower[k], upper[k]))? {
Ok(rail) => rails.push(rail),
Err(reason) => {
decline = Some(reason);
break;
}
}
}
if probed_any {
obj.eval_cost(rho).map_err(|err| {
EstimationError::RemlOptimizationFailed(format!(
"{}: failed to restore the objective to the certified point after \
asymptote-rail probing: {err}",
inputs.context
))
})?;
}
if let Some(reason) = decline {
return Ok(Err(reason));
}
if rails.is_empty() {
return Ok(Err(
"no railed coordinate produced a certifiable tail".to_string()
));
}
Ok(Ok((
interior_projected_grad_norm,
effective_interior_bound,
rails,
)))
}
pub(crate) fn certify_interior_stationarity(
gradient: &Array1<f64>,
hessian: &Array2<f64>,
interior_indices: &[usize],
stationarity_bound: f64,
objective_tol: f64,
) -> Result<(f64, f64), String> {
let interior_grad_norm = interior_indices
.iter()
.map(|&k| gradient[k] * gradient[k])
.sum::<f64>()
.sqrt();
if interior_grad_norm <= stationarity_bound {
return Ok((interior_grad_norm, stationarity_bound));
}
let m = interior_indices.len();
let mut sub_h = Array2::<f64>::zeros((m, m));
let mut sub_g = Array1::<f64>::zeros(m);
for (i, &ri) in interior_indices.iter().enumerate() {
sub_g[i] = gradient[ri];
for (j, &rj) in interior_indices.iter().enumerate() {
sub_h[[i, j]] = hessian[[ri, rj]];
}
}
match newton_predicted_decrease(&sub_h, &sub_g) {
Some(predicted_decrease) if predicted_decrease.is_finite() && predicted_decrease > 0.0 => {
if predicted_decrease <= objective_tol {
let curvature_grad_bound =
interior_grad_norm * (objective_tol / predicted_decrease).sqrt();
if curvature_grad_bound.is_finite() && curvature_grad_bound >= interior_grad_norm {
return Ok((interior_grad_norm, curvature_grad_bound));
}
}
Err(format!(
"interior not stationary: |Pg_int|={interior_grad_norm:.3e} > bound {stationarity_bound:.3e}, sub-block Newton decrement {predicted_decrease:.3e} > cost resolution {objective_tol:.3e}"
))
}
_ => Err(format!(
"interior not stationary: |Pg_int|={interior_grad_norm:.3e} > bound {stationarity_bound:.3e} and the interior sub-block yields no PD Newton decrement"
)),
}
}
const TAIL_SNAP_CURVATURE_BAND: (f64, f64) = (0.25, 4.0);
#[derive(Debug)]
enum TailSnapOutcome {
TailStationaryAtPoint {
rails: Vec<RailCoordinate>,
interior_projected_grad_norm: f64,
effective_interior_bound: f64,
},
Snapped(Array1<f64>),
ConfirmedNeedsReseed(Array1<f64>),
Declined(String),
}
const TAIL_SNAP_DRIFT_REL: f64 = 1.0e-2;
fn try_tail_snap_to_rail(
obj: &mut dyn OuterObjective,
inputs: &AsymptoteRailInputs<'_>,
) -> Result<TailSnapOutcome, EstimationError> {
let rho = inputs.rho;
let gradient = inputs.projected_gradient;
let hessian = inputs.hessian;
let (lower, upper) = inputs.bounds;
let n = gradient.len();
if rho.len() != n
|| hessian.nrows() != n
|| hessian.ncols() != n
|| lower.len() < n
|| upper.len() < n
{
return Ok(TailSnapOutcome::Declined("shape mismatch".to_string()));
}
let mut candidates: Vec<(usize, AsymptoteSide)> = Vec::new();
let mut rejected: Vec<String> = Vec::new();
for k in 0..n {
if inputs.railed.contains(&k) {
continue;
}
let g_k = gradient[k];
let side = match AsymptoteSide::from_gradient(g_k, inputs.stationarity_bound) {
Some(side) => side,
None => continue,
};
let probe_span = ASYMPTOTE_PROBE_COUNT as f64;
let deep_enough = match side {
AsymptoteSide::Upper => upper[k] - rho[k] <= probe_span,
AsymptoteSide::Lower => rho[k] - lower[k] <= probe_span,
};
if !deep_enough {
rejected.push(format!(
"k={k}: ρ={:.2} more than {probe_span:.0} e-folds inside the box",
rho[k]
));
continue;
}
let h_kk = hessian[[k, k]];
let ratio = h_kk.abs() / g_k.abs();
if !(TAIL_SNAP_CURVATURE_BAND.0..=TAIL_SNAP_CURVATURE_BAND.1).contains(&ratio) {
rejected.push(format!(
"k={k}: g={g_k:.3e} H_kk={h_kk:.3e} |ratio|={ratio:.3e} outside tie band"
));
continue;
}
candidates.push((k, side));
}
if candidates.is_empty() {
return Ok(TailSnapOutcome::Declined(if rejected.is_empty() {
"no super-bound coordinate".to_string()
} else {
format!(
"no candidate passed the curvature tie ({})",
rejected.join("; ")
)
}));
}
let excluded: Vec<usize> = inputs
.railed
.iter()
.copied()
.chain(candidates.iter().map(|(k, _)| *k))
.collect();
if certificate_hessian_is_psd_off_railed_above_gradient_floor(hessian, &excluded, gradient)
!= Some(true)
{
return Ok(TailSnapOutcome::Declined(
"interior Hessian sub-block not PSD".to_string(),
));
}
let beta_norm = inputs
.terminal_beta
.map(|b| b.dot(b).sqrt())
.filter(|v| v.is_finite())
.unwrap_or(0.0);
let mut tol =
AsymptoteTolerances::exp4_rail_bands(ASYMPTOTE_ESTIMAND_REL_TOL * (1.0 + beta_norm));
tol.tail_drift_rel = TAIL_SNAP_DRIFT_REL;
let mut decline: Option<String> = None;
let mut at_point_rails: Vec<RailCoordinate> = Vec::new();
for (k, side) in &candidates {
let verdict = match probe_tail_window(obj, rho, *k, *side, &tol, (lower[*k], upper[*k]))? {
(Some(window), rows) => match assess_coordinate(&window, &tol) {
AsymptoteVerdict::CertifiedAtAsymptote {
side: assessed_side,
tail_constant,
estimand_travel_bound,
..
} => {
let extrapolated_gap = match assessed_side {
AsymptoteSide::Upper => tail_constant * (-rho[*k]).exp(),
AsymptoteSide::Lower => tail_constant * rho[*k].exp(),
};
if extrapolated_gap.is_finite() && extrapolated_gap <= inputs.stationarity_bound
{
at_point_rails.push(RailCoordinate {
index: *k,
side: assessed_side,
tail_constant,
value_gap: extrapolated_gap,
estimand_travel_bound,
noise_margin: tol.tail_noise_floor,
});
}
None
}
AsymptoteVerdict::OnTailNotYetEquivalent { .. } => None,
AsymptoteVerdict::NoAsymptote { reason } => {
Some(format!("{reason}; probes: {rows}"))
}
},
(None, rows) => Some(format!(
"no finite-difference-clean tail run; probes: {rows}"
)),
};
if let Some(reason) = verdict {
decline = Some(format!("candidate k={k} tail unconfirmed: {reason}"));
break;
}
}
let mut joint_face_confirmed = false;
if decline.is_some() && candidates.len() >= 2 {
let (window, joint_rows) =
probe_joint_tail_window(obj, rho, &candidates, &tol, (lower, upper))?;
match window.as_ref().map(|w| assess_coordinate(w, &tol)) {
Some(AsymptoteVerdict::CertifiedAtAsymptote {
tail_constant,
estimand_travel_bound,
..
}) => {
let r0 = candidates
.iter()
.map(|(k, side)| match side {
AsymptoteSide::Upper => rho[*k],
AsymptoteSide::Lower => -rho[*k],
})
.sum::<f64>()
/ candidates.len() as f64;
let joint_gap = tail_constant * (-r0).exp();
if joint_gap.is_finite() && joint_gap <= inputs.stationarity_bound {
at_point_rails = candidates
.iter()
.map(|(k, side)| RailCoordinate {
index: *k,
side: *side,
tail_constant,
value_gap: joint_gap,
estimand_travel_bound,
noise_margin: tol.tail_noise_floor,
})
.collect();
}
joint_face_confirmed = true;
decline = None;
}
Some(AsymptoteVerdict::OnTailNotYetEquivalent { .. }) => {
joint_face_confirmed = true;
decline = None;
}
Some(AsymptoteVerdict::NoAsymptote { reason }) => {
log::info!(
"[CERTIFICATE] joint {}-coordinate face: pencil-constant run \
confirmed but estimand not settled at the checkpoint \
({reason}); snapping the face for re-certification",
candidates.len(),
);
joint_face_confirmed = true;
decline = None;
}
None => {
decline = Some(format!(
"{}; joint {}-coordinate face: no finite-difference-clean run; joint probes: {joint_rows}",
decline.take().unwrap_or_default(),
candidates.len(),
));
}
}
}
obj.eval_cost(rho).map_err(|err| {
EstimationError::RemlOptimizationFailed(format!(
"{}: failed to restore the objective to the certified point after \
tail-snap probing: {err}",
inputs.context
))
})?;
if let Some(reason) = decline {
return Ok(TailSnapOutcome::Declined(reason));
}
let interior_indices: Vec<usize> = (0..n)
.filter(|k| !inputs.railed.contains(k) && !candidates.iter().any(|(c, _)| c == k))
.collect();
let interior_grad_norm = interior_indices
.iter()
.map(|&k| gradient[k] * gradient[k])
.sum::<f64>()
.sqrt();
if at_point_rails.len() == candidates.len() {
if let Ok((interior_projected_grad_norm, effective_interior_bound)) =
certify_interior_stationarity(
gradient,
hessian,
&interior_indices,
inputs.stationarity_bound,
inputs.objective_tol,
)
{
return Ok(TailSnapOutcome::TailStationaryAtPoint {
rails: at_point_rails,
interior_projected_grad_norm,
effective_interior_bound,
});
}
}
let mut snapped = rho.clone();
for (k, side) in &candidates {
snapped[*k] = match side {
AsymptoteSide::Upper => upper[*k],
AsymptoteSide::Lower => lower[*k],
};
}
if interior_grad_norm <= inputs.stationarity_bound && !joint_face_confirmed {
Ok(TailSnapOutcome::Snapped(snapped))
} else {
Ok(TailSnapOutcome::ConfirmedNeedsReseed(snapped))
}
}
fn build_and_assess_rail_coordinate(
obj: &mut dyn OuterObjective,
rho: &Array1<f64>,
coord: usize,
side: AsymptoteSide,
tol: &AsymptoteTolerances,
domain: (f64, f64),
) -> Result<Result<RailCoordinate, String>, EstimationError> {
let window = match probe_tail_window(obj, rho, coord, side, tol, domain)? {
(Some(window), _) => window,
(None, rows) => {
return Ok(Err(format!(
"k={coord}: no finite-difference-clean tail window; probes {rows}"
)));
}
};
match assess_coordinate(&window, tol) {
AsymptoteVerdict::CertifiedAtAsymptote {
side,
tail_constant,
value_gap,
estimand_travel_bound,
} => Ok(Ok(RailCoordinate {
index: coord,
side,
tail_constant,
value_gap,
estimand_travel_bound,
noise_margin: tol.tail_noise_floor,
})),
other => Ok(Err(format!("k={coord}: tail verdict {other:?}"))),
}
}
fn detect_wrong_rail_pullback(
obj: &mut dyn OuterObjective,
rho: &Array1<f64>,
coord: usize,
side: AsymptoteSide,
tol: &AsymptoteTolerances,
domain: (f64, f64),
) -> Result<Option<f64>, EstimationError> {
const PROBE_DELTA: f64 = 1.0;
const PROBE_DOMAIN_MARGIN: f64 = 1.0e-6;
let sign = match side {
AsymptoteSide::Upper => -1.0,
AsymptoteSide::Lower => 1.0,
};
let mut rows: Vec<(f64, f64)> = Vec::new();
for j in 1..=ASYMPTOTE_PROBE_COUNT {
let stepped = rho[coord] + sign * (j as f64) * PROBE_DELTA;
if stepped <= domain.0 + PROBE_DOMAIN_MARGIN || stepped >= domain.1 - PROBE_DOMAIN_MARGIN {
break;
}
let mut probe = rho.clone();
probe[coord] = stepped;
let eval = match obj.eval_with_order(&probe, OuterEvalOrder::ValueAndGradient) {
Ok(eval) => eval,
Err(_) => break,
};
if !eval.cost.is_finite() || coord >= eval.gradient.len() || !eval.gradient[coord].is_finite()
{
break;
}
rows.push((stepped, eval.gradient[coord]));
}
if rows.len() < MIN_TAIL_SAMPLES {
return Ok(None);
}
let constants: Vec<f64> = rows
.iter()
.map(|(r, g)| side.tail_constant(*r, *g))
.collect();
let element_clean: Vec<bool> = rows
.iter()
.zip(&constants)
.map(|((_, g), c)| {
c.is_finite() && *c < -tol.tail_noise_floor && g.abs() > tol.interior_grad_tol
})
.collect();
let mut best: Option<(usize, usize)> = None;
for a in 0..rows.len() {
if !element_clean[a] {
continue;
}
for b in a..rows.len() {
if !element_clean[b] {
break;
}
if b - a + 1 < MIN_TAIL_SAMPLES {
continue;
}
if !run_drift_within_band(&constants[a..=b], tol.tail_drift_rel) {
continue;
}
match best {
Some((ba, bb)) if bb - ba + 1 >= b - a + 1 => {}
_ => best = Some((a, b)),
}
}
}
Ok(best.map(|(_, b)| rows[b].0))
}
fn probe_tail_window(
obj: &mut dyn OuterObjective,
rho: &Array1<f64>,
coord: usize,
side: AsymptoteSide,
tol: &AsymptoteTolerances,
domain: (f64, f64),
) -> Result<(Option<AsymptoteWindow>, String), EstimationError> {
const PROBE_DELTA: f64 = 1.0;
const PROBE_DOMAIN_MARGIN: f64 = 1.0e-6;
let sign = match side {
AsymptoteSide::Upper => -1.0,
AsymptoteSide::Lower => 1.0,
};
let mut rows: Vec<(f64, f64, Option<Array1<f64>>)> = Vec::new();
for j in 1..=ASYMPTOTE_PROBE_COUNT {
let stepped = rho[coord] + sign * (j as f64) * PROBE_DELTA;
if stepped <= domain.0 + PROBE_DOMAIN_MARGIN || stepped >= domain.1 - PROBE_DOMAIN_MARGIN {
break;
}
let mut probe = rho.clone();
probe[coord] = stepped;
let eval = match obj.eval_with_order(&probe, OuterEvalOrder::ValueAndGradient) {
Ok(eval) => eval,
Err(_) => break,
};
if !eval.cost.is_finite()
|| coord >= eval.gradient.len()
|| !eval.gradient[coord].is_finite()
{
break;
}
rows.push((probe[coord], eval.gradient[coord], eval.inner_beta_hint));
}
let rows_summary = rows
.iter()
.map(|(r, g, _)| {
format!(
"(ρ={r:.2}, g={g:.3e}, ĉ={:.3e})",
side.tail_constant(*r, *g)
)
})
.collect::<Vec<_>>()
.join(" ");
if rows.len() < MIN_TAIL_SAMPLES {
return Ok((None, rows_summary));
}
let constants: Vec<f64> = rows
.iter()
.map(|(r, g, _)| side.tail_constant(*r, *g))
.collect();
let element_clean: Vec<bool> = rows
.iter()
.zip(&constants)
.map(|((_, g, _), c)| {
c.is_finite() && *c > tol.tail_noise_floor && g.abs() > tol.interior_grad_tol
})
.collect();
let mut best: Option<(usize, usize)> = None;
for a in 0..rows.len() {
if !element_clean[a] {
continue;
}
for b in a..rows.len() {
if !element_clean[b] {
break;
}
if b - a + 1 < MIN_TAIL_SAMPLES {
continue;
}
if !run_drift_within_band(&constants[a..=b], tol.tail_drift_rel) {
continue;
}
let len = b - a + 1;
match best {
Some((ba, bb)) if bb - ba + 1 >= len => {}
_ => best = Some((a, b)),
}
}
}
let (a, b) = match best {
Some(run) => run,
None => return Ok((None, rows_summary)),
};
let mut window = AsymptoteWindow::with_capacity(b - a + 1);
for r in (a..=b).rev() {
let (rho_r, grad_r, beta_r) = &rows[r];
let coef_step_norm = match (beta_r, rows.get(r + 1).map(|row| &row.2)) {
(Some(cur), Some(Some(farther))) if cur.len() == farther.len() => {
(cur - farther).iter().map(|v| v * v).sum::<f64>().sqrt()
}
_ => 0.0,
};
window.push(AsymptoteSample {
rho: *rho_r,
grad: *grad_r,
coef_step_norm,
});
}
Ok((Some(window), rows_summary))
}
fn probe_joint_tail_window(
obj: &mut dyn OuterObjective,
rho: &Array1<f64>,
face: &[(usize, AsymptoteSide)],
tol: &AsymptoteTolerances,
bounds: (&Array1<f64>, &Array1<f64>),
) -> Result<(Option<AsymptoteWindow>, String), EstimationError> {
const PROBE_DELTA: f64 = 1.0;
const PROBE_DOMAIN_MARGIN: f64 = 1.0e-6;
let (lower, upper) = bounds;
let direction: Vec<(usize, f64)> = face
.iter()
.map(|(k, side)| {
(
*k,
match side {
AsymptoteSide::Upper => 1.0,
AsymptoteSide::Lower => -1.0,
},
)
})
.collect();
let r0 = direction
.iter()
.map(|(k, u)| u * rho[*k])
.sum::<f64>()
/ direction.len() as f64;
let mut rows: Vec<(f64, f64, Option<Array1<f64>>)> = Vec::new();
for j in 1..=ASYMPTOTE_PROBE_COUNT {
let step = (j as f64) * PROBE_DELTA;
let mut probe = rho.clone();
let mut in_domain = true;
for (k, u) in &direction {
let stepped = rho[*k] - u * step;
if stepped <= lower[*k] + PROBE_DOMAIN_MARGIN
|| stepped >= upper[*k] - PROBE_DOMAIN_MARGIN
{
in_domain = false;
break;
}
probe[*k] = stepped;
}
if !in_domain {
break;
}
let eval = match obj.eval_with_order(&probe, OuterEvalOrder::ValueAndGradient) {
Ok(eval) => eval,
Err(_) => break,
};
if !eval.cost.is_finite() {
break;
}
let mut g_u = 0.0;
let mut finite = true;
for (k, u) in &direction {
match eval.gradient.get(*k) {
Some(g) if g.is_finite() => g_u += u * g,
_ => {
finite = false;
break;
}
}
}
if !finite {
break;
}
rows.push((r0 - step, g_u, eval.inner_beta_hint));
}
let rows_summary = rows
.iter()
.map(|(r, g, _)| {
format!(
"(r={r:.2}, dV/dt={g:.3e}, ĉ={:.3e})",
AsymptoteSide::Upper.tail_constant(*r, *g)
)
})
.collect::<Vec<_>>()
.join(" ");
if rows.len() < MIN_TAIL_SAMPLES {
return Ok((None, rows_summary));
}
let constants: Vec<f64> = rows
.iter()
.map(|(r, g, _)| AsymptoteSide::Upper.tail_constant(*r, *g))
.collect();
let element_clean: Vec<bool> = rows
.iter()
.zip(&constants)
.map(|((_, g, _), c)| {
c.is_finite() && *c > tol.tail_noise_floor && g.abs() > tol.interior_grad_tol
})
.collect();
let mut best: Option<(usize, usize)> = None;
for a in 0..rows.len() {
if !element_clean[a] {
continue;
}
for b in a..rows.len() {
if !element_clean[b] {
break;
}
if b - a + 1 < MIN_TAIL_SAMPLES {
continue;
}
if !run_drift_within_band(&constants[a..=b], tol.tail_drift_rel) {
continue;
}
let len = b - a + 1;
match best {
Some((ba, bb)) if bb - ba + 1 >= len => {}
_ => best = Some((a, b)),
}
}
}
let (a, b) = match best {
Some(run) => run,
None => return Ok((None, rows_summary)),
};
let mut window = AsymptoteWindow::with_capacity(b - a + 1);
for r in (a..=b).rev() {
let (rho_r, grad_r, beta_r) = &rows[r];
let coef_step_norm = match (beta_r, rows.get(r + 1).map(|row| &row.2)) {
(Some(cur), Some(Some(farther))) if cur.len() == farther.len() => {
(cur - farther).iter().map(|v| v * v).sum::<f64>().sqrt()
}
_ => 0.0,
};
window.push(AsymptoteSample {
rho: *rho_r,
grad: *grad_r,
coef_step_norm,
});
}
Ok((Some(window), rows_summary))
}
fn run_drift_within_band(constants: &[f64], band: f64) -> bool {
if constants.len() < MIN_TAIL_SAMPLES {
return false;
}
let mut sum = 0.0_f64;
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
for &c in constants {
if !c.is_finite() {
return false;
}
sum += c;
lo = lo.min(c);
hi = hi.max(c);
}
let mean = sum / constants.len() as f64;
if !(mean.abs() > 0.0) {
return false;
}
(hi - lo) / mean.abs() <= band
}
pub(crate) fn compute_rho_uncertainty_diagnostic(
obj: &mut dyn OuterObjective,
config: &OuterConfig,
context: &str,
result: &mut OuterResult,
) -> crate::rho_uncertainty::RhoUncertaintyDiagnostic {
let terminal_cap_guard = config
.outer_inner_cap
.as_ref()
.map(TerminalInnerCapGuard::lift);
let diagnostic =
compute_rho_uncertainty_diagnostic_at_terminal_fidelity(obj, config, context, result);
drop(terminal_cap_guard);
diagnostic
}
fn compute_rho_uncertainty_diagnostic_at_terminal_fidelity(
obj: &mut dyn OuterObjective,
config: &OuterConfig,
context: &str,
result: &mut OuterResult,
) -> crate::rho_uncertainty::RhoUncertaintyDiagnostic {
let cap = obj.capability();
let layout = cap.theta_layout();
let rho_dim = layout.rho_dim();
let gate = crate::rho_uncertainty::RhoUncertaintyCostGate {
sample_count: 32,
problem_size: config.rho_uncertainty_problem_size,
};
if let Err(reason) = crate::rho_uncertainty::cost_gate_allows(rho_dim, gate) {
return crate::rho_uncertainty::RhoUncertaintyDiagnostic::skipped(reason, 0);
}
if result.rho.len() != layout.n_params {
return crate::rho_uncertainty::RhoUncertaintyDiagnostic::skipped(
format!(
"final outer point length {} does not match objective dimension {}",
result.rho.len(),
layout.n_params
),
0,
);
}
if !cap.hessian.is_analytic() {
return crate::rho_uncertainty::RhoUncertaintyDiagnostic::skipped(
"outer Hessian is not analytic; rho-uncertainty diagnostic needs exact curvature",
0,
);
}
let final_eval = match obj.eval_with_order(&result.rho, OuterEvalOrder::ValueGradientHessian) {
Ok(eval) => eval,
Err(err) => {
return crate::rho_uncertainty::RhoUncertaintyDiagnostic::skipped(
format!("final exact Hessian evaluation failed: {err}"),
1,
);
}
};
let hessian = match final_eval.hessian.materialize_dense() {
Ok(Some(hessian)) => hessian,
Ok(None) => {
return crate::rho_uncertainty::RhoUncertaintyDiagnostic::skipped(
"exact outer Hessian unavailable at fitted rho",
1,
);
}
Err(message) => {
return crate::rho_uncertainty::RhoUncertaintyDiagnostic::skipped(
format!("exact outer Hessian materialization failed: {message}"),
1,
);
}
};
if hessian.nrows() != layout.n_params || hessian.ncols() != layout.n_params {
return crate::rho_uncertainty::RhoUncertaintyDiagnostic::skipped(
format!(
"exact outer Hessian shape {}x{} does not match objective dimension {}",
hessian.nrows(),
hessian.ncols(),
layout.n_params
),
1,
);
}
if result.final_hessian.is_none() && hessian.iter().all(|v| v.is_finite()) {
result.final_hessian = Some(hessian.clone());
}
let mut hessian_rho = Array2::<f64>::zeros((rho_dim, rho_dim));
for row in 0..rho_dim {
for col in 0..rho_dim {
hessian_rho[[row, col]] = hessian[[row, col]];
}
}
let rho_hat = result.rho.slice(ndarray::s![..rho_dim]).to_owned();
let theta_hat = result.rho.clone();
let cost_hat = final_eval.cost;
let final_beta_hint = final_eval.inner_beta_hint.clone();
let diagnostic = {
let mut served_hat_cost = false;
let mut criterion = |rho: &Array1<f64>| -> Option<f64> {
let is_hat = rho.len() == rho_hat.len()
&& rho
.iter()
.zip(rho_hat.iter())
.all(|(&left, &right)| left.to_bits() == right.to_bits());
if is_hat && !served_hat_cost {
served_hat_cost = true;
return Some(cost_hat);
}
let mut theta = theta_hat.clone();
for idx in 0..rho_dim {
theta[idx] = rho[idx];
}
if let Some(beta) = final_beta_hint.as_ref()
&& obj.seed_inner_state(beta).is_err()
{
return None;
}
obj.eval_cost(&theta).ok()
};
crate::rho_uncertainty::rho_uncertainty_diagnostic(
&rho_hat,
&hessian_rho,
gate,
&mut criterion,
)
};
match &diagnostic.status {
crate::rho_uncertainty::RhoUncertaintyStatus::NoEvidenceOfHeavyTails => {
log::info!(
"[RHO uncertainty] {context}: no heavy-tail evidence at sampled rho proposals k_hat={:.3} evals={}",
diagnostic.k_hat.unwrap_or(f64::NAN),
diagnostic.n_evaluations,
);
}
crate::rho_uncertainty::RhoUncertaintyStatus::HeavyTailsDetected { k_hat } => {
log::warn!(
"[RHO uncertainty] {context}: heavy rho-importance tail detected k_hat={:.3} evals={}",
k_hat,
diagnostic.n_evaluations,
);
}
crate::rho_uncertainty::RhoUncertaintyStatus::Skipped { reason } => {
log::info!("[RHO uncertainty] {context}: skipped ({reason})");
}
}
diagnostic
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OperatorTrustRegionStopReason {
Converged,
RejectFloor,
IterationBudget,
CostStallFlatValley,
RoutingMismatch,
}
const OUTER_CERTIFY_RESUME_BUDGET: usize = 16;
const OUTER_SADDLE_ESCAPE_BUDGET: usize = 3;
const CERTIFY_RESUME_PROGRESS_REL: f64 = 32.0 * f64::EPSILON;
pub(crate) fn run_outer(
obj: &mut dyn OuterObjective,
config: &OuterConfig,
context: &str,
) -> Result<OuterResult, EstimationError> {
if let Some(keys) = config.rho_canonical_keys.as_ref()
&& let Some(perm) = canonical_permutation(keys)
{
let canonical_config = canonicalize_outer_config(config, &perm);
let mut canonical_obj = CanonicalizedObjective::new(obj, perm.clone());
let result = run_outer(&mut canonical_obj, &canonical_config, context)?;
return Ok(outer_result_to_native(result, &perm));
}
let mut result = run_outer_uncertified(obj, config, context)?;
if obj.begin_exact_polish() {
let pilot_iterations = result.iterations;
let mut exact_config = config.clone();
exact_config.initial_rho = Some(result.rho.clone());
exact_config.heuristic_lambdas = None;
exact_config.seed_config.max_seeds = 1;
exact_config.seed_config.seed_budget = 1;
exact_config.screen_initial_rho = false;
exact_config.operator_initial_trust_radius = result.operator_trust_radius;
exact_config.warm_start_outer_hessian = result.final_hessian.clone();
log::info!(
"[OUTER] {context}: sampled derivative pilot completed after {} iteration(s); \
continuing from its checkpoint on the exact full-data measure",
pilot_iterations,
);
let mut polished = run_outer_uncertified(obj, &exact_config, context)?;
polished.iterations = polished.iterations.saturating_add(pilot_iterations);
result = polished;
}
let certify_diagnose_and_install = |obj: &mut dyn OuterObjective,
result: &mut OuterResult|
-> Result<OuterCriterionCertificate, EstimationError> {
result.rho_uncertainty_diagnostic = Some(compute_rho_uncertainty_diagnostic(
obj, config, context, result,
));
let terminal_cap_guard = config
.outer_inner_cap
.as_ref()
.map(TerminalInnerCapGuard::lift);
if terminal_cap_guard.is_some() || obj.owns_terminal_coefficient_mode() {
obj.reset();
}
let terminal_installation = obj.finalize_outer_result(&result.rho, &result.plan_used);
let terminal_inner_converged = inner_solve_converged(config.outer_inner_cap.as_ref());
drop(terminal_cap_guard);
terminal_installation?;
if !terminal_inner_converged {
return Err(outer_nonconvergence_error(
context,
"final outer state installation did not converge at full inner fidelity",
result,
result.final_grad_norm,
outer_gradient_tolerance(config).abs,
));
}
certify_outer_optimality(obj, config, context, result)
};
let mut resumes_remaining = OUTER_CERTIFY_RESUME_BUDGET;
let mut saddle_escapes_remaining: usize = OUTER_SADDLE_ESCAPE_BUDGET;
let certificate = loop {
let claimed_converged = result.converged;
match certify_diagnose_and_install(obj, &mut result) {
Ok(certificate) => break certificate,
Err(refusal) => {
let saddle_escape_reseed = result.saddle_escape_reseed.take();
let resume_from_saddle_escape = saddle_escape_reseed.is_some();
let tail_snap_reseed = if resume_from_saddle_escape {
result.tail_snap_reseed.take();
None
} else {
result.tail_snap_reseed.take()
};
let resume_from_tail_snap = tail_snap_reseed.is_some();
let higher_precedence_reseed = resume_from_saddle_escape || resume_from_tail_snap;
let wrong_rail_reseed = if higher_precedence_reseed {
result.wrong_rail_reseed.take();
None
} else {
result.wrong_rail_reseed.take()
};
let resume_from_wrong_rail = wrong_rail_reseed.is_some();
let active_set_reseed = if higher_precedence_reseed || resume_from_wrong_rail {
result.active_set_reseed.take();
None
} else {
result.active_set_reseed.take()
};
let resume_from_active_set = active_set_reseed.is_some();
let active_set_rho = active_set_reseed.as_ref().map(|a| a.rho.clone());
let active_set_bounds = active_set_reseed.map(|a| a.bounds);
if (!claimed_converged
&& !resume_from_saddle_escape
&& !resume_from_tail_snap
&& !resume_from_wrong_rail
&& !resume_from_active_set)
|| resumes_remaining == 0
|| (resume_from_saddle_escape && saddle_escapes_remaining == 0)
{
return Err(refusal);
}
resumes_remaining -= 1;
if resume_from_saddle_escape {
saddle_escapes_remaining -= 1;
}
let prior_iterations = result.iterations;
let prior_value = result.final_value;
log::info!(
"[OUTER] {context}: analytic certification refused after \
{prior_iterations} iteration(s) (final_value={prior_value:.6e}); re-running \
seeded {} so the in-loop tolerance anchors to the terminal cost scale \
({resumes_remaining} resume(s) left after this one; #2273/#2374/#2155)",
if resume_from_saddle_escape {
"off the negative-curvature saddle ridge"
} else if resume_from_tail_snap {
"at the confirmed-tail snapped face"
} else if resume_from_wrong_rail {
"at the wrong-rail coordinate's clean-band interior scale"
} else if resume_from_active_set {
"with the poisoned rail frozen so the interior polishes in the reduced box"
} else {
"at the refused checkpoint"
}
);
let mut retry_cfg = config.clone();
retry_cfg.initial_rho = Some(
saddle_escape_reseed
.or(tail_snap_reseed)
.or(wrong_rail_reseed)
.or(active_set_rho)
.unwrap_or_else(|| result.rho.clone()),
);
if let Some(frozen_bounds) = active_set_bounds {
retry_cfg.bounds = Some(frozen_bounds);
}
retry_cfg.heuristic_lambdas = None;
retry_cfg.seed_config.max_seeds = 1;
retry_cfg.seed_config.seed_budget = 1;
retry_cfg.screen_initial_rho = false;
let fresh_metric = resume_from_saddle_escape
|| resume_from_tail_snap
|| resume_from_wrong_rail
|| resume_from_active_set;
retry_cfg.operator_initial_trust_radius = if fresh_metric {
None
} else {
result.operator_trust_radius
};
retry_cfg.warm_start_outer_hessian = if fresh_metric {
None
} else {
result.final_hessian.clone()
};
obj.reset();
match run_outer_uncertified(obj, &retry_cfg, context) {
Ok(mut retried) => {
retried.iterations = retried.iterations.saturating_add(prior_iterations);
let improved = certify_resume_made_progress(
prior_value,
retried.final_value,
CERTIFY_RESUME_PROGRESS_REL,
);
result = retried;
if !improved {
resumes_remaining = 0;
}
}
Err(_) => return Err(refusal),
}
}
}
};
result.criterion_certificate = Some(certificate);
Ok(result)
}
fn canonicalize_outer_config(config: &OuterConfig, perm: &[usize]) -> OuterConfig {
let permute_vec = |v: &[f64]| -> Vec<f64> {
if v.len() == perm.len() {
perm.iter().map(|&i| v[i]).collect()
} else {
v.to_vec()
}
};
let permute_arr = |a: &Array1<f64>| -> Array1<f64> {
if a.len() == perm.len() {
Array1::from_iter(perm.iter().map(|&i| a[i]))
} else {
a.clone()
}
};
let mut canonical = config.clone();
canonical.rho_canonical_keys = None;
if let Some(initial) = config.initial_rho.as_ref() {
canonical.initial_rho = Some(permute_arr(initial));
}
if let Some(bound) = config.initial_inner_seed.as_ref() {
canonical.initial_inner_seed = Some(BoundInnerSeed {
theta: permute_arr(&bound.theta),
beta: bound.beta.clone(),
});
}
if let Some(h) = config.heuristic_lambdas.as_ref() {
canonical.heuristic_lambdas = Some(permute_vec(h));
}
if let Some((lower, upper)) = config.bounds.as_ref() {
canonical.bounds = Some((permute_arr(lower), permute_arr(upper)));
}
if let Some(h) = config.warm_start_outer_hessian.as_ref()
&& h.nrows() == perm.len()
&& h.ncols() == perm.len()
{
let mut hc = Array2::<f64>::zeros((perm.len(), perm.len()));
for (a, &ia) in perm.iter().enumerate() {
for (b, &ib) in perm.iter().enumerate() {
hc[[a, b]] = h[[ia, ib]];
}
}
canonical.warm_start_outer_hessian = Some(hc);
}
canonical
}
pub(crate) fn run_outer_uncertified(
obj: &mut dyn OuterObjective,
config: &OuterConfig,
context: &str,
) -> Result<OuterResult, EstimationError> {
let cap = primary_capability_for_config(obj.capability(), config, context);
cap.validate_layout(context)?;
{
let (bound_lo, bound_hi) = outer_bounds_template(config, cap.n_params);
for i in 0..bound_lo.len() {
if !(bound_lo[i].is_finite() && bound_hi[i].is_finite()) {
return Err(EstimationError::InvalidInput(format!(
"{context}: outer rho bounds are non-finite at coordinate {i}: \
lower={}, upper={}",
bound_lo[i], bound_hi[i]
)));
}
if bound_lo[i] > bound_hi[i] {
return Err(EstimationError::InvalidInput(format!(
"{context}: outer rho bounds are inverted at coordinate {i}: \
lower bound {} exceeds upper bound {}",
bound_lo[i], bound_hi[i]
)));
}
}
outer_bounds(&bound_lo, &bound_hi)
.map_err(|err| EstimationError::InvalidInput(format!("{context}: {err}")))?;
}
if let Some(initial_rho) = config.initial_rho.as_ref() {
cap.theta_layout()
.validate_point_len(initial_rho, "initial outer seed")
.map_err(|err| match err {
ObjectiveEvalError::Recoverable { message }
| ObjectiveEvalError::Fatal { message } => {
EstimationError::RemlOptimizationFailed(format!("{context}: {message}"))
}
})?;
}
crate::estimate::reml::outer_eval::clear_outer_ift_residual_energy_for_fit();
if let Some(result) = run_per_atom_efs_if_frontier(obj, config, context)? {
if result.converged {
return Ok(result);
}
return Err(outer_nonconvergence_error(
context,
"per-atom EFS exhausted its iteration budget before the fixed-point step converged",
&result,
None,
outer_gradient_tolerance(config).abs,
));
}
if cap.n_params == 0 {
let cost = obj.eval_cost(&Array1::zeros(0))?;
let the_plan = plan(&cap);
return Ok(outer_result_with_gradient_norm(
Array1::zeros(0),
cost,
0,
Some(0.0),
true,
the_plan,
));
}
let fallback_attempts = match config.fallback_policy {
FallbackPolicy::Automatic => automatic_fallback_attempts(&cap),
FallbackPolicy::Disabled => Vec::new(),
};
let mut attempts: Vec<OuterCapability> = Vec::with_capacity(1 + fallback_attempts.len());
attempts.push(cap.clone());
for degraded in fallback_attempts {
attempts.push(degraded);
}
let mut last_error: Option<EstimationError> = None;
let mut best_checkpoint: Option<OuterResult> = None;
for (attempt_idx, attempt_cap) in attempts.iter().enumerate() {
let the_plan = plan(attempt_cap);
if attempt_idx > 0 {
log::debug!("[OUTER] {context}: primary plan failed; falling back to {the_plan}");
}
log_plan(context, attempt_cap, &the_plan);
obj.reset();
let mut arc_retries_left: u32 = if matches!(the_plan.solver, Solver::Arc) {
2
} else {
0
};
let mut retry_config: Option<OuterConfig> = None;
let mut prev_attempt_grad_norm: Option<f64> = None;
let outcome = loop {
let active_config_owned: OuterConfig =
retry_config.clone().unwrap_or_else(|| config.clone());
let active_config: &OuterConfig = &active_config_owned;
match run_outer_with_plan(obj, active_config, context, attempt_cap, &the_plan, true) {
Ok(PlanRunOutcome::Converged(result)) => break Ok(result),
Ok(PlanRunOutcome::Exhausted(result)) => {
if arc_retries_left == 0
|| matches!(
result.operator_stop_reason,
Some(
OperatorTrustRegionStopReason::RejectFloor
| OperatorTrustRegionStopReason::CostStallFlatValley
)
)
{
break Ok(result);
}
let Some(cur_grad_norm) = result.final_grad_norm else {
log::info!(
"[OUTER] {context}: ARC attempt exhausted budget at \
iter={} cost={:.6e} without a final gradient norm; \
falling through to degraded plan",
result.iterations,
result.final_value,
);
break Ok(result);
};
if let Some(prev_g) = prev_attempt_grad_norm {
let progressed = cur_grad_norm.is_finite()
&& prev_g.is_finite()
&& cur_grad_norm < 0.5 * prev_g;
if !progressed {
log::info!(
"[OUTER] {context}: ARC retry stalled at \
iter={} cost={:.6e} |g|={:.6e} (prev |g|={:.6e}); \
deterministic replay suspected, falling through \
to degraded plan",
result.iterations,
result.final_value,
cur_grad_norm,
prev_g,
);
break Ok(result);
}
}
let next_trust_radius =
sanitized_operator_trust_restart_radius(result.operator_trust_radius);
log::info!(
"[OUTER] {context}: ARC attempt exhausted budget at \
iter={} cost={:.6e} |g|={:.6e}; resuming from last \
rho + trust_radius={:?}, inner-PIRLS uncapped \
(objective caches wiped; operator-TR Cauchy/Newton \
state is not resumable)",
result.iterations,
result.final_value,
cur_grad_norm,
next_trust_radius,
);
let cap_feedback = active_config.outer_inner_cap.clone();
let mut next = active_config.clone();
prev_attempt_grad_norm = Some(cur_grad_norm);
next.initial_rho = Some(result.rho.clone());
next.operator_initial_trust_radius = next_trust_radius;
retry_config = Some(next);
arc_retries_left -= 1;
obj.reset();
if let Some(feedback) = cap_feedback.as_ref() {
feedback.cap.store(0, Ordering::Relaxed);
}
}
Err(e) => break Err(e),
}
};
match outcome {
Ok(result) => {
if result.converged {
return Ok(result);
}
let improves_checkpoint = result.final_value.is_finite()
&& best_checkpoint.as_ref().is_none_or(|checkpoint| {
!checkpoint.final_value.is_finite()
|| result.final_value < checkpoint.final_value
});
if improves_checkpoint {
best_checkpoint = Some(result);
}
let message = format!(
"{context}: attempt {} (plan={the_plan}) exhausted without convergence",
attempt_idx + 1
);
log::debug!("[OUTER] {message}; trying degraded fallback plan");
last_error = Some(EstimationError::RemlOptimizationFailed(message));
}
Err(e) => {
if e.is_fatal_outer_evaluation() {
return Err(e);
}
log::debug!(
"[OUTER] {context}: attempt {} (plan={the_plan}) failed: {e}",
attempt_idx + 1
);
last_error = Some(e);
}
}
}
if let Some(checkpoint) = best_checkpoint {
return Ok(checkpoint);
}
Err(last_error.unwrap_or_else(|| {
EstimationError::RemlOptimizationFailed(format!("all plan attempts exhausted ({context})"))
}))
}
pub fn is_per_atom_efs_frontier(cap: &OuterCapability) -> bool {
crate::estimate::reml::per_atom_efs::per_atom_efs_eligible(cap)
}
pub(crate) fn run_per_atom_efs_if_frontier(
obj: &mut dyn OuterObjective,
config: &OuterConfig,
context: &str,
) -> Result<Option<OuterResult>, EstimationError> {
let cap = primary_capability_for_config(obj.capability(), config, context);
cap.validate_layout(context)?;
if !is_per_atom_efs_frontier(&cap) {
return Ok(None);
}
let the_plan = plan(&cap);
let rho_dim = cap.theta_layout().rho_dim();
let (lower, upper) = outer_bounds_template(config, cap.n_params);
let seed = match config.initial_rho.as_ref() {
Some(initial) if initial.len() == cap.n_params => initial.clone(),
_ => {
let generated = crate::seeding::generate_rho_candidates(
cap.n_params,
config.heuristic_lambdas.as_deref(),
&config.seed_config,
)?;
match generated.into_iter().next() {
Some(first) => first,
None => Array1::<f64>::zeros(cap.n_params),
}
}
};
log::info!(
"[OUTER] {context}: frontier ρ-scaling (rho_dim={rho_dim}) → per-atom decoupled EFS primary"
);
let pa_cfg = crate::estimate::reml::per_atom_efs::PerAtomEfsConfig::new(
config.tolerance,
config.max_iter,
lower,
upper,
);
let topology = crate::estimate::reml::per_atom_efs::SharedBorderTopology::disjoint(rho_dim);
obj.reset();
install_matching_initial_inner_seed(obj, config, &seed, context)?;
let result =
crate::estimate::reml::per_atom_efs::run_per_atom_efs(obj, &seed, &pa_cfg, &topology)?;
Ok(Some(result.into_outer_result(the_plan)))
}
#[cfg(test)]
#[path = "inverted_rho_box_tests.rs"]
mod inverted_rho_box_tests;
pub(crate) fn outer_bounds(lo: &Array1<f64>, hi: &Array1<f64>) -> Result<Bounds, EstimationError> {
Bounds::new(lo.clone(), hi.clone(), 1e-6).map_err(|err| {
EstimationError::InvalidInput(format!("outer rho bounds are invalid: {err}"))
})
}
pub(crate) fn outer_bounds_template(config: &OuterConfig, n: usize) -> (Array1<f64>, Array1<f64>) {
config.bounds.clone().unwrap_or_else(|| {
(
Array1::<f64>::from_elem(n, -config.rho_bound),
Array1::<f64>::from_elem(n, config.rho_bound),
)
})
}
pub(super) fn install_objective_domain(
config: &mut OuterConfig,
n_params: usize,
objective_lower: Option<Array1<f64>>,
objective_upper: Option<Array1<f64>>,
) -> Result<(), EstimationError> {
let (mut lower, mut upper) = outer_bounds_template(config, n_params);
if lower.len() != n_params || upper.len() != n_params {
return Err(EstimationError::InvalidInput(format!(
"outer configured bounds dimension mismatch: parameters={n_params}, lower={}, upper={}",
lower.len(),
upper.len(),
)));
}
if let Some(domain) = objective_lower.as_ref()
&& domain.len() != n_params
{
return Err(EstimationError::InvalidInput(format!(
"outer objective-domain lower-bound dimension mismatch: parameters={n_params}, lower={}",
domain.len()
)));
}
if let Some(domain) = objective_upper.as_ref()
&& domain.len() != n_params
{
return Err(EstimationError::InvalidInput(format!(
"outer objective-domain upper-bound dimension mismatch: parameters={n_params}, upper={}",
domain.len()
)));
}
for index in 0..n_params {
if let Some(domain) = objective_lower.as_ref() {
let value = domain[index];
if !value.is_finite() {
return Err(EstimationError::InvalidInput(format!(
"outer objective-domain lower bound[{index}] must be finite; got {value}"
)));
}
lower[index] = lower[index].max(value);
}
if let Some(domain) = objective_upper.as_ref() {
let value = domain[index];
if !value.is_finite() {
return Err(EstimationError::InvalidInput(format!(
"outer objective-domain upper bound[{index}] must be finite; got {value}"
)));
}
upper[index] = upper[index].min(value);
}
if !(lower[index].is_finite() && upper[index].is_finite() && lower[index] < upper[index]) {
return Err(EstimationError::InvalidInput(format!(
"outer objective-domain intersection is empty or non-finite at coordinate {index}: lower={}, upper={}",
lower[index], upper[index]
)));
}
}
config.bounds = Some((lower, upper));
Ok(())
}
pub(crate) fn outer_tolerance(value: f64) -> Result<Tolerance, EstimationError> {
Tolerance::new(value)
.map_err(|err| EstimationError::InvalidInput(format!("outer tolerance is invalid: {err}")))
}
pub(crate) fn outer_rel_cost_floor(config: &OuterConfig) -> f64 {
config
.rel_cost_tolerance
.unwrap_or(config.tolerance * 1.0e-2)
.max(COST_STALL_REL_TOL_FLOOR)
}
pub(crate) fn certify_resume_made_progress(
prior_value: f64,
retried_value: f64,
rel_cost_floor: f64,
) -> bool {
let floor = rel_cost_floor * (1.0 + prior_value.abs().min(retried_value.abs()));
retried_value.is_finite() && retried_value < prior_value - floor
}
pub(crate) fn outer_gradient_tolerance(config: &OuterConfig) -> GradientTolerance {
let abs = config
.objective_scale
.map(|scale| config.tolerance.max(scale * f64::EPSILON.sqrt()))
.unwrap_or(config.tolerance);
GradientTolerance {
abs,
rel_initial_grad: None,
rel_cost: Some(config.rel_cost_tolerance.unwrap_or(config.tolerance)),
projected: true,
}
}
pub(crate) fn outer_max_iterations(value: usize) -> Result<MaxIterations, EstimationError> {
MaxIterations::new(value)
.map_err(|err| EstimationError::InvalidInput(format!("outer max_iter is invalid: {err}")))
}
pub(crate) fn sanitized_operator_trust_restart_radius(radius: Option<f64>) -> Option<f64> {
radius
.filter(|value| value.is_finite() && *value > 0.0)
.map(|value| value.max(OPERATOR_TRUST_RESTART_RADIUS_FLOOR))
}
pub(crate) fn bfgs_axis_step_caps(
config: &OuterConfig,
layout: OuterThetaLayout,
) -> Option<Array1<f64>> {
if config.bfgs_step_cap.is_none() && config.bfgs_step_cap_psi.is_none() {
return None;
}
let mut caps = Array1::from_elem(layout.n_params, f64::INFINITY);
if let Some(cap) = config.bfgs_step_cap {
for i in 0..layout.rho_dim() {
caps[i] = cap;
}
}
if let Some(cap) = config.bfgs_step_cap_psi {
for i in layout.rho_dim()..layout.n_params {
caps[i] = cap;
}
}
Some(caps)
}
pub(crate) enum FixedPointOuterRunError {
SeedRejected(EstimationError),
ImmediateFallback(EstimationError),
Failed(EstimationError),
}
pub(crate) fn run_fixed_point_outer_solver(
obj: &mut dyn OuterObjective,
layout: OuterThetaLayout,
barrier_config: Option<BarrierConfig>,
config: &OuterConfig,
context: &str,
seed: &Array1<f64>,
the_plan: OuterPlan,
label: &str,
failure_prefix: &str,
) -> Result<OuterResult, FixedPointOuterRunError> {
let recurrent_incumbent_exit = Arc::new(Mutex::new(None));
let mut objective = OuterFixedPointBridge {
obj,
layout,
barrier_config,
fixed_point_tolerance: config.tolerance,
consecutive_psi_zero_iters: 0,
last_restored_incumbent_streak: None,
recurrent_incumbent_exit: Arc::clone(&recurrent_incumbent_exit),
};
let seed_sample = match objective.eval_step(seed) {
Ok(sample) => sample,
Err(ObjectiveEvalError::Recoverable { message }) => {
let err = EstimationError::RemlOptimizationFailed(message);
if requests_immediate_first_order_fallback(&err.to_string()) {
return Err(FixedPointOuterRunError::ImmediateFallback(err));
}
return Err(FixedPointOuterRunError::SeedRejected(err));
}
Err(ObjectiveEvalError::Fatal { message }) => {
return Err(FixedPointOuterRunError::Failed(
EstimationError::fatal_outer_evaluation(
"outer fixed-point seed evaluation",
EstimationError::RemlOptimizationFailed(message),
),
));
}
};
let (lo, hi) = outer_bounds_template(config, layout.n_params);
let bounds = outer_bounds(&lo, &hi).map_err(FixedPointOuterRunError::Failed)?;
let tol = outer_tolerance(config.tolerance).map_err(FixedPointOuterRunError::Failed)?;
let max_iter =
outer_max_iterations(config.max_iter).map_err(FixedPointOuterRunError::Failed)?;
let mut optimizer = FixedPoint::new(seed.clone(), objective)
.with_initial_sample(seed.clone(), seed_sample)
.with_bounds(bounds)
.with_tolerance(tol)
.with_max_iterations(max_iter);
match optimizer.run() {
Ok(sol) => {
let mut result = solution_into_outer_result(sol, true, the_plan);
if let Some(consecutive_restores) =
recurrent_incumbent_exit.lock().ok().and_then(|slot| *slot)
{
result.converged_via = Some(OuterConvergedVia::RecurrentIncumbent {
consecutive_restores,
});
}
Ok(result)
}
Err(FixedPointError::MaxIterationsReached { last_solution }) => {
log::warn!(
"[OUTER warning] {context}: {label} hit max_iter={} at final_value={:.6e} step_norm={:.3e}",
config.max_iter,
last_solution.final_value,
last_solution.final_gradient_norm.unwrap_or(f64::NAN),
);
Ok(solution_into_outer_result(*last_solution, false, the_plan))
}
Err(FixedPointError::ObjectiveFailed { message }) => Err(FixedPointOuterRunError::Failed(
EstimationError::fatal_outer_evaluation(
"outer fixed-point evaluation",
EstimationError::RemlOptimizationFailed(message),
),
)),
Err(e) => Err(FixedPointOuterRunError::Failed(
EstimationError::RemlOptimizationFailed(format!("{failure_prefix}: {e:?}")),
)),
}
}
#[cfg(test)]
mod asymptote_rail_certify_tests {
use super::*;
use ndarray::array;
fn upper_tail_objective(c: f64, a: f64, drift_amp: f64) -> impl OuterObjective {
let problem = OuterProblem::new(1).with_gradient(Derivative::Analytic);
problem.build_objective(
(),
move |_: &mut (), rho: &Array1<f64>| {
let r = rho[0];
let c_eff = c + drift_amp * r;
Ok((c_eff * (-r).exp()).abs())
},
move |_: &mut (), rho: &Array1<f64>| {
let r = rho[0];
let c_eff = c + drift_amp * r;
Ok(OuterEval {
cost: (c_eff * (-r).exp()).abs(),
gradient: array![-c_eff * (-r).exp()],
hessian: HessianValue::Unavailable,
inner_beta_hint: Some(array![a * (-r).exp()]),
})
},
None::<fn(&mut ())>,
None::<fn(&mut (), &Array1<f64>) -> Result<EfsEval, EstimationError>>,
)
}
#[test]
fn asymptote_rail_mints_on_exact_tail_law() {
let mut obj = upper_tail_objective(6723.0, 1.0, 0.0);
let rho = array![29.9];
let tol = AsymptoteTolerances::exp4_rail_bands(1.0e-2);
let rail = build_and_assess_rail_coordinate(
&mut obj,
&rho,
0,
AsymptoteSide::Upper,
&tol,
(f64::NEG_INFINITY, f64::INFINITY),
)
.expect("probing the tail-law objective must not error")
.expect("an exact exponential tail must certify a rail");
assert_eq!(rail.index, 0);
assert_eq!(rail.side, AsymptoteSide::Upper);
assert!(
(rail.tail_constant - 6723.0).abs() / 6723.0 < 1.0e-6,
"recovered ĉ={} should equal c=6723",
rail.tail_constant,
);
assert!(rail.value_gap.is_finite() && rail.value_gap >= 0.0);
assert!(rail.estimand_travel_bound.is_finite() && rail.estimand_travel_bound >= 0.0);
}
#[test]
fn asymptote_rail_refuses_on_drifting_constant() {
let mut obj = upper_tail_objective(6723.0, 1.0, 3000.0);
let rho = array![29.9];
let tol = AsymptoteTolerances::exp4_rail_bands(1.0e-2);
let verdict = build_and_assess_rail_coordinate(
&mut obj,
&rho,
0,
AsymptoteSide::Upper,
&tol,
(f64::NEG_INFINITY, f64::INFINITY),
)
.expect("probing must not error");
assert!(
verdict.is_err(),
"a drifting ĉ must not certify a tail, got {verdict:?}",
);
}
#[test]
fn wrong_rail_pullback_fires_on_inward_descent_2392() {
let c = 6723.0;
let problem = OuterProblem::new(1).with_gradient(Derivative::Analytic);
let mut obj = problem.build_objective(
(),
move |_: &mut (), rho: &Array1<f64>| Ok(-c * (-rho[0]).exp()),
move |_: &mut (), rho: &Array1<f64>| {
Ok(OuterEval {
cost: -c * (-rho[0]).exp(),
gradient: array![c * (-rho[0]).exp()],
hessian: HessianValue::Unavailable,
inner_beta_hint: Some(array![(-rho[0]).exp()]),
})
},
None::<fn(&mut ())>,
None::<fn(&mut (), &Array1<f64>) -> Result<EfsEval, EstimationError>>,
);
let rho = array![29.9];
let tol = AsymptoteTolerances::exp4_rail_bands(1.0e-2);
let target = detect_wrong_rail_pullback(
&mut obj,
&rho,
0,
AsymptoteSide::Upper,
&tol,
(-30.0, 30.0),
)
.expect("probing the wrong-rail objective must not error")
.expect("an inward-descent rail must publish a pull-back target");
assert!(
target < rho[0] && target.is_finite(),
"the reseed must move the coordinate INWARD (ρ down), got {target}",
);
}
#[test]
fn wrong_rail_pullback_refuses_a_genuine_upper_tail_2392() {
let mut obj = upper_tail_objective(6723.0, 1.0, 0.0);
let rho = array![29.9];
let tol = AsymptoteTolerances::exp4_rail_bands(1.0e-2);
let verdict = detect_wrong_rail_pullback(
&mut obj,
&rho,
0,
AsymptoteSide::Upper,
&tol,
(-30.0, 30.0),
)
.expect("probing must not error");
assert!(
verdict.is_none(),
"a genuine λ→∞ tail (ĉ>0) must not be pulled off its rail, got {verdict:?}",
);
}
#[test]
fn interior_psd_gate_floors_tail_residue_but_keeps_genuine_saddles_2349() {
let hessian = array![[0.2828, 0.0004], [0.0004, -1.0216e-3]];
let gradient = array![-1.057, -1.0228e-3];
let excluded = [0usize];
assert_eq!(
certificate_hessian_is_psd_off_railed(&hessian, &excluded),
Some(false),
"raw gate must see the corrupted sub-resolution entry as indefinite"
);
assert_eq!(
certificate_hessian_is_psd_off_railed_above_gradient_floor(
&hessian, &excluded, &gradient
),
Some(true),
"the gradient floor must absorb the O(|g|) trace-pair residue"
);
let saddle = array![[0.2828, 0.0004], [0.0004, -0.5]];
assert_eq!(
certificate_hessian_is_psd_off_railed_above_gradient_floor(
&saddle, &excluded, &gradient
),
Some(false),
"a genuine interior saddle dwarfs the bound-scale floor and refuses"
);
}
fn joint_face_objective(c: f64, a: f64) -> impl OuterObjective {
let problem = OuterProblem::new(2).with_gradient(Derivative::Analytic);
problem.build_objective(
(),
move |_: &mut (), rho: &Array1<f64>| Ok(c * (-(rho[0] + rho[1]) / 2.0).exp()),
move |_: &mut (), rho: &Array1<f64>| {
let v = c * (-(rho[0] + rho[1]) / 2.0).exp();
Ok(OuterEval {
cost: v,
gradient: array![-0.5 * v, -0.5 * v],
hessian: HessianValue::Unavailable,
inner_beta_hint: Some(array![a * (-(rho[0] + rho[1]) / 2.0).exp()]),
})
},
None::<fn(&mut ())>,
None::<fn(&mut (), &Array1<f64>) -> Result<EfsEval, EstimationError>>,
)
}
#[test]
fn joint_face_tail_certifies_where_single_coordinate_law_drifts_2349() {
let c = 1.2 * (7.5_f64).exp();
let rho = array![8.0, 7.0];
let tol = {
let mut t = AsymptoteTolerances::exp4_rail_bands(1.0e-2);
t.tail_drift_rel = TAIL_SNAP_DRIFT_REL;
t
};
let bounds = (Array1::from_elem(2, -12.0), Array1::from_elem(2, 12.0));
let mut obj = joint_face_objective(c, 1.0e-9);
let (single_window, _) = probe_tail_window(
&mut obj,
&rho,
0,
AsymptoteSide::Upper,
&tol,
(bounds.0[0], bounds.1[0]),
)
.expect("single-coordinate probing must not error");
assert!(
single_window.is_none(),
"the marginal pencil constant drifts e^(1/2) per e-fold and must not \
produce a finite-difference-clean run"
);
let (joint_window, _) = probe_joint_tail_window(
&mut obj,
&rho,
&[(0, AsymptoteSide::Upper), (1, AsymptoteSide::Upper)],
&tol,
(&bounds.0, &bounds.1),
)
.expect("joint probing must not error");
let window = joint_window.expect("the joint face law is exactly exponential");
match assess_coordinate(&window, &tol) {
AsymptoteVerdict::CertifiedAtAsymptote { tail_constant, .. } => {
assert!(
(tail_constant - c).abs() / c < 1.0e-6,
"joint pencil constant must recover c: got {tail_constant}, want {c}"
);
}
other => panic!("joint face must certify, got {other:?}"),
}
let g = -0.5 * c * (-7.5_f64).exp();
let gradient = array![g, g];
let hessian = array![[g.abs(), 0.0], [0.0, g.abs()]];
let outcome = try_tail_snap_to_rail(
&mut obj,
&AsymptoteRailInputs {
rho: &rho,
projected_gradient: &gradient,
railed: &[],
hessian: &hessian,
bounds: &bounds,
terminal_beta: None,
stationarity_bound: 1.0e-3,
objective_tol: 1.0e-8,
context: "joint-face guard test",
},
)
.expect("tail snap must not error");
match outcome {
TailSnapOutcome::Snapped(snapped) | TailSnapOutcome::ConfirmedNeedsReseed(snapped) => {
assert_eq!(
snapped,
array![12.0, 12.0],
"both face coordinates must snap to their upper rails"
);
}
other => panic!(
"the joint face must confirm and snap (Snapped/ConfirmedNeedsReseed), got {other:?}"
),
}
}
#[test]
fn joint_face_with_unsettled_estimand_snaps_for_recertification_2349() {
let c = 1.2 * (7.5_f64).exp();
let problem = OuterProblem::new(2).with_gradient(Derivative::Analytic);
let mut obj = problem.build_objective(
(),
move |_: &mut (), rho: &Array1<f64>| Ok(c * (-(rho[0] + rho[1]) / 2.0).exp()),
move |_: &mut (), rho: &Array1<f64>| {
let v = c * (-(rho[0] + rho[1]) / 2.0).exp();
Ok(OuterEval {
cost: v,
gradient: array![-0.5 * v, -0.5 * v],
hessian: HessianValue::Unavailable,
inner_beta_hint: Some(array![0.1 * (rho[0] + rho[1])]),
})
},
None::<fn(&mut ())>,
None::<fn(&mut (), &Array1<f64>) -> Result<EfsEval, EstimationError>>,
);
let rho = array![8.0, 7.0];
let g = -0.5 * c * (-7.5_f64).exp();
let gradient = array![g, g];
let hessian = array![[g.abs(), 0.0], [0.0, g.abs()]];
let bounds = (Array1::from_elem(2, -12.0), Array1::from_elem(2, 12.0));
let outcome = try_tail_snap_to_rail(
&mut obj,
&AsymptoteRailInputs {
rho: &rho,
projected_gradient: &gradient,
railed: &[],
hessian: &hessian,
bounds: &bounds,
terminal_beta: None,
stationarity_bound: 1.0e-3,
objective_tol: 1.0e-8,
context: "joint-face unsettled-estimand guard test",
},
)
.expect("tail snap must not error");
match outcome {
TailSnapOutcome::Snapped(snapped) | TailSnapOutcome::ConfirmedNeedsReseed(snapped) => {
assert_eq!(
snapped,
array![12.0, 12.0],
"a confirmed joint law with unsettled estimand must snap the face"
);
}
other => panic!("expected a face snap, got {other:?}"),
}
}
#[test]
fn joint_face_fallback_refuses_a_non_face_2349() {
let problem = OuterProblem::new(2).with_gradient(Derivative::Analytic);
let (c0, drift, c1) = (3.0e3, 2.0e3, 5.0e2);
let mut obj = problem.build_objective(
(),
move |_: &mut (), rho: &Array1<f64>| {
Ok((c0 + drift * rho[0]) * (-rho[0]).exp() + c1 * (-2.0 * rho[1]).exp())
},
move |_: &mut (), rho: &Array1<f64>| {
let e0 = (-rho[0]).exp();
let e1 = (-2.0 * rho[1]).exp();
Ok(OuterEval {
cost: (c0 + drift * rho[0]) * e0 + c1 * e1,
gradient: array![
drift * e0 - (c0 + drift * rho[0]) * e0,
-2.0 * c1 * e1
],
hessian: HessianValue::Unavailable,
inner_beta_hint: Some(array![1.0e-9 * e0]),
})
},
None::<fn(&mut ())>,
None::<fn(&mut (), &Array1<f64>) -> Result<EfsEval, EstimationError>>,
);
let rho = array![8.0, 7.0];
let g0 = drift * (-8.0_f64).exp() - (c0 + drift * 8.0) * (-8.0_f64).exp();
let g1 = -2.0 * c1 * (-14.0_f64).exp();
let gradient = array![g0, g1];
let hessian = array![[g0.abs(), 0.0], [0.0, g1.abs()]];
let bounds = (Array1::from_elem(2, -12.0), Array1::from_elem(2, 12.0));
let outcome = try_tail_snap_to_rail(
&mut obj,
&AsymptoteRailInputs {
rho: &rho,
projected_gradient: &gradient,
railed: &[],
hessian: &hessian,
bounds: &bounds,
terminal_beta: None,
stationarity_bound: 1.0e-9,
objective_tol: 1.0e-8,
context: "non-face guard test",
},
)
.expect("tail snap must not error");
match outcome {
TailSnapOutcome::Declined(reason) => {
assert!(
reason.contains("joint 2-coordinate face"),
"the decline must carry the joint-face evidence, got: {reason}"
);
}
other => panic!("a non-face must decline, got {other:?}"),
}
}
#[test]
fn tail_probe_ladder_never_leaves_the_coordinate_box_2388() {
let c = 6723.0_f64;
let box_lower = 12.0_f64;
let probed = std::sync::Arc::new(std::sync::Mutex::new(Vec::<f64>::new()));
let probed_in_eval = std::sync::Arc::clone(&probed);
let problem = OuterProblem::new(1).with_gradient(Derivative::Analytic);
let mut obj = problem.build_objective(
(),
move |_: &mut (), rho: &Array1<f64>| Ok((c * (-rho[0]).exp()).abs()),
move |_: &mut (), rho: &Array1<f64>| {
let r = rho[0];
probed_in_eval.lock().expect("probe log").push(r);
let grad = if r <= box_lower + 1.0e-8 {
0.0
} else {
-c * (-r).exp()
};
Ok(OuterEval {
cost: (c * (-r).exp()).abs(),
gradient: array![grad],
hessian: HessianValue::Unavailable,
inner_beta_hint: Some(array![(-r).exp()]),
})
},
None::<fn(&mut ())>,
None::<fn(&mut (), &Array1<f64>) -> Result<EfsEval, EstimationError>>,
);
let rho = array![29.9];
let tol = AsymptoteTolerances::exp4_rail_bands(1.0e-2);
let rail = build_and_assess_rail_coordinate(
&mut obj,
&rho,
0,
AsymptoteSide::Upper,
&tol,
(box_lower, 30.0),
)
.expect("probing must not error")
.expect("the in-domain rows alone must certify the exact tail");
assert!(
(rail.tail_constant - c).abs() / c < 1.0e-6,
"recovered ĉ={} should equal c={c}",
rail.tail_constant,
);
let seen = probed.lock().expect("probe log").clone();
assert!(
!seen.is_empty() && seen.iter().all(|&r| r > box_lower),
"no probe may leave the λ-selection domain (lower bound {box_lower}): {seen:?}",
);
}
fn upper_tail_with_interior(c: f64, a: f64) -> impl OuterObjective {
let problem = OuterProblem::new(2).with_gradient(Derivative::Analytic);
problem.build_objective(
(),
move |_: &mut (), rho: &Array1<f64>| Ok((c * (-rho[0]).exp()).abs()),
move |_: &mut (), rho: &Array1<f64>| {
let r = rho[0];
Ok(OuterEval {
cost: (c * (-r).exp()).abs(),
gradient: array![-c * (-r).exp(), 0.0],
hessian: HessianValue::Unavailable,
inner_beta_hint: Some(array![a * (-r).exp(), 0.0]),
})
},
None::<fn(&mut ())>,
None::<fn(&mut (), &Array1<f64>) -> Result<EfsEval, EstimationError>>,
)
}
#[test]
fn asymptote_rail_requires_psd_interior_sub_block() {
let rho = array![29.9, 0.0];
let projected = array![0.0, 0.0];
let bounds = (array![-30.0, -30.0], array![30.0, 30.0]);
let railed = [0usize];
let mut obj = upper_tail_with_interior(6723.0, 1.0);
let hessian_psd = array![[1.0, 0.0], [0.0, 2.0]];
let inputs_psd = AsymptoteRailInputs {
rho: &rho,
projected_gradient: &projected,
railed: &railed,
hessian: &hessian_psd,
bounds: &bounds,
terminal_beta: None,
stationarity_bound: 1.0e-6,
objective_tol: 1.0e-5,
context: "asymptote-rail psd test",
};
let minted = try_certify_asymptote_rail(&mut obj, &inputs_psd)
.expect("certification must not error");
let (interior_norm, effective_bound, rails) =
minted.expect("PSD interior + confirmed tail must mint");
assert!(interior_norm <= 1.0e-6);
assert!(
effective_bound >= interior_norm,
"the admitting bound must cover the interior norm"
);
assert_eq!(rails.len(), 1);
assert_eq!(rails[0].index, 0);
let hessian_indefinite = array![[1.0, 0.0], [0.0, -2.0]];
let inputs_indefinite = AsymptoteRailInputs {
hessian: &hessian_indefinite,
..inputs_psd
};
let refused = try_certify_asymptote_rail(&mut obj, &inputs_indefinite)
.expect("certification must not error");
assert!(
refused.is_err(),
"indefinite interior curvature must refuse the rail certificate, got {refused:?}",
);
let reason = refused.unwrap_err();
assert!(
reason.contains("not PSD") || reason.contains("interior"),
"the decline must name the refusing gate, got: {reason}"
);
}
}
#[cfg(test)]
mod certify_resume_progress_tests {
use super::{
CERTIFY_RESUME_PROGRESS_REL, OuterConfig, certify_resume_made_progress,
outer_rel_cost_floor,
};
fn config_with_rel_cost(rel_cost: Option<f64>, tolerance: f64) -> OuterConfig {
OuterConfig {
tolerance,
rel_cost_tolerance: rel_cost,
..OuterConfig::default()
}
}
#[test]
fn rel_cost_floor_prefers_explicit_then_scaled_tolerance_never_below_hard_floor() {
let explicit = config_with_rel_cost(Some(1.0e-3), 1.0e-5);
assert_eq!(outer_rel_cost_floor(&explicit), 1.0e-3);
let derived = config_with_rel_cost(None, 1.0e-2);
assert!((outer_rel_cost_floor(&derived) - 1.0e-4).abs() <= 1.0e-16);
let tiny = config_with_rel_cost(Some(1.0e-30), 1.0e-30);
assert_eq!(outer_rel_cost_floor(&tiny), super::COST_STALL_REL_TOL_FLOOR);
}
#[test]
fn strict_descent_past_the_floor_is_progress() {
let floor = 1.0e-4;
assert!(certify_resume_made_progress(342.0, 300.0, floor));
assert!(certify_resume_made_progress(1.0e6, 1.0e3, floor));
}
#[test]
fn flat_or_uphill_reseed_is_not_progress() {
let floor = 1.0e-4;
assert!(!certify_resume_made_progress(100.0, 100.0, floor));
assert!(!certify_resume_made_progress(100.0, 100.5, floor));
let cost = 1.0e4;
let sub_floor = floor * (1.0 + cost) * 0.5;
assert!(!certify_resume_made_progress(cost, cost - sub_floor, floor));
}
#[test]
fn floor_anchors_on_the_smaller_cost_magnitude() {
let floor = 1.0e-4;
assert!(certify_resume_made_progress(1.0e-2, 1.0e-3, floor));
}
#[test]
fn non_finite_retried_is_never_progress() {
let floor = 1.0e-4;
assert!(!certify_resume_made_progress(100.0, f64::NAN, floor));
assert!(!certify_resume_made_progress(100.0, f64::INFINITY, floor));
assert!(!certify_resume_made_progress(100.0, f64::NEG_INFINITY, floor));
}
#[test]
fn roundoff_gate_admits_the_tiny_flat_valley_crawl_step() {
let rel = CERTIFY_RESUME_PROGRESS_REL;
assert!(certify_resume_made_progress(342.0730, 342.0580, rel));
assert!(certify_resume_made_progress(455.40, 455.40 - 5.0e-4, rel));
}
#[test]
fn roundoff_gate_rejects_noise_and_non_descent() {
let rel = CERTIFY_RESUME_PROGRESS_REL;
assert!(!certify_resume_made_progress(455.40, 455.40, rel));
let noise = 4.0 * f64::EPSILON * (1.0 + 455.40);
assert!(!certify_resume_made_progress(455.40, 455.40 - noise, rel));
assert!(!certify_resume_made_progress(455.40, 455.41, rel));
assert!(!certify_resume_made_progress(455.40, f64::NAN, rel));
}
}