@@ -468,6 +468,91 @@ def gen_batch_initial_conditions(
468468 return batch_initial_conditions
469469
470470
471+ def gen_optimal_input_initial_conditions (
472+ acq_function : AcquisitionFunction ,
473+ bounds : Tensor ,
474+ q : int ,
475+ num_restarts : int ,
476+ raw_samples : int ,
477+ fixed_features : dict [int , float ] | None = None ,
478+ options : dict [str , bool | float | int ] | None = None ,
479+ inequality_constraints : list [tuple [Tensor , Tensor , float ]] | None = None ,
480+ equality_constraints : list [tuple [Tensor , Tensor , float ]] | None = None ,
481+ ):
482+ options = options or {}
483+ device = bounds .device
484+ if not hasattr (acq_function , "optimal_inputs" ):
485+ raise AttributeError (
486+ "gen_optimal_input_initial_conditions can only be used with "
487+ "an AcquisitionFunction that has an optimal_inputs attribute."
488+ )
489+ frac_random : float = options .get ("frac_random" , 0.0 )
490+ if not 0 <= frac_random <= 1 :
491+ raise ValueError (
492+ f"frac_random must take on values in (0,1). Value: { frac_random } "
493+ )
494+
495+ batch_limit = options .get ("batch_limit" )
496+ num_optima = acq_function .optimal_inputs .shape [:- 1 ].numel ()
497+ suggestions = acq_function .optimal_inputs .reshape (num_optima , - 1 )
498+ X = torch .empty (0 , q , bounds .shape [1 ], dtype = bounds .dtype )
499+ num_random = round (raw_samples * frac_random )
500+ if num_random > 0 :
501+ X_rnd = sample_q_batches_from_polytope (
502+ n = num_random ,
503+ q = q ,
504+ bounds = bounds ,
505+ n_burnin = options .get ("n_burnin" , 10000 ),
506+ n_thinning = options .get ("n_thinning" , 32 ),
507+ equality_constraints = equality_constraints ,
508+ inequality_constraints = inequality_constraints ,
509+ )
510+ X = torch .cat ((X , X_rnd ))
511+
512+ if num_random < raw_samples :
513+ X_perturbed = sample_points_around_best (
514+ acq_function = acq_function ,
515+ n_discrete_points = q * (raw_samples - num_random ),
516+ sigma = options .get ("sample_around_best_sigma" , 1e-2 ),
517+ bounds = bounds ,
518+ best_X = suggestions ,
519+ )
520+ X_perturbed = X_perturbed .view (
521+ raw_samples - num_random , q , bounds .shape [- 1 ]
522+ ).cpu ()
523+ X = torch .cat ((X , X_perturbed ))
524+
525+ if options .get ("sample_around_best" , False ):
526+ X_best = sample_points_around_best (
527+ acq_function = acq_function ,
528+ n_discrete_points = q * raw_samples ,
529+ sigma = options .get ("sample_around_best_sigma" , 1e-2 ),
530+ bounds = bounds ,
531+ )
532+ X_best = X_best .view (raw_samples , q , bounds .shape [- 1 ]).cpu ()
533+ X = torch .cat ((X , X_best ))
534+
535+ with torch .no_grad ():
536+ if batch_limit is None :
537+ batch_limit = X .shape [0 ]
538+ # Evaluate the acquisition function on `X_rnd` using `batch_limit`
539+ # sized chunks.
540+ acq_vals = torch .cat (
541+ [
542+ acq_function (x_ .to (device = device )).cpu ()
543+ for x_ in X .split (split_size = batch_limit , dim = 0 )
544+ ],
545+ dim = 0 ,
546+ )
547+ idx = boltzmann_sample (
548+ function_values = acq_vals ,
549+ num_samples = num_restarts ,
550+ eta = options .get ("eta" , 2.0 ),
551+ )
552+ # set the respective initial conditions to the sampled optimizers
553+ return X [idx ]
554+
555+
471556def gen_one_shot_kg_initial_conditions (
472557 acq_function : qKnowledgeGradient ,
473558 bounds : Tensor ,
@@ -1136,6 +1221,7 @@ def sample_points_around_best(
11361221 best_pct : float = 5.0 ,
11371222 subset_sigma : float = 1e-1 ,
11381223 prob_perturb : float | None = None ,
1224+ best_X : Tensor | None = None ,
11391225) -> Tensor | None :
11401226 r"""Find best points and sample nearby points.
11411227
@@ -1154,60 +1240,62 @@ def sample_points_around_best(
11541240 An optional `n_discrete_points x d`-dim tensor containing the
11551241 sampled points. This is None if no baseline points are found.
11561242 """
1157- X = get_X_baseline (acq_function = acq_function )
1158- if X is None :
1159- return
1160- with torch .no_grad ():
1161- try :
1162- posterior = acq_function .model .posterior (X )
1163- except AttributeError :
1164- warnings .warn (
1165- "Failed to sample around previous best points." ,
1166- BotorchWarning ,
1167- stacklevel = 3 ,
1168- )
1243+ if best_X is None :
1244+ X = get_X_baseline (acq_function = acq_function )
1245+ if X is None :
11691246 return
1170- mean = posterior .mean
1171- while mean .ndim > 2 :
1172- # take average over batch dims
1173- mean = mean .mean (dim = 0 )
1174- try :
1175- f_pred = acq_function .objective (mean )
1176- # Some acquisition functions do not have an objective
1177- # and for some acquisition functions the objective is None
1178- except (AttributeError , TypeError ):
1179- f_pred = mean
1180- if hasattr (acq_function , "maximize" ):
1181- # make sure that the optimiztaion direction is set properly
1182- if not acq_function .maximize :
1183- f_pred = - f_pred
1184- try :
1185- # handle constraints for EHVI-based acquisition functions
1186- constraints = acq_function .constraints
1187- if constraints is not None :
1188- neg_violation = - torch .stack (
1189- [c (mean ).clamp_min (0.0 ) for c in constraints ], dim = - 1
1190- ).sum (dim = - 1 )
1191- feas = neg_violation == 0
1192- if feas .any ():
1193- f_pred [~ feas ] = float ("-inf" )
1194- else :
1195- # set objective equal to negative violation
1196- f_pred = neg_violation
1197- except AttributeError :
1198- pass
1199- if f_pred .ndim == mean .ndim and f_pred .shape [- 1 ] > 1 :
1200- # multi-objective
1201- # find pareto set
1202- is_pareto = is_non_dominated (f_pred )
1203- best_X = X [is_pareto ]
1204- else :
1205- if f_pred .shape [- 1 ] == 1 :
1206- f_pred = f_pred .squeeze (- 1 )
1207- n_best = max (1 , round (X .shape [0 ] * best_pct / 100 ))
1208- # the view() is to ensure that best_idcs is not a scalar tensor
1209- best_idcs = torch .topk (f_pred , n_best ).indices .view (- 1 )
1210- best_X = X [best_idcs ]
1247+ with torch .no_grad ():
1248+ try :
1249+ posterior = acq_function .model .posterior (X )
1250+ except AttributeError :
1251+ warnings .warn (
1252+ "Failed to sample around previous best points." ,
1253+ BotorchWarning ,
1254+ stacklevel = 3 ,
1255+ )
1256+ return
1257+ mean = posterior .mean
1258+ while mean .ndim > 2 :
1259+ # take average over batch dims
1260+ mean = mean .mean (dim = 0 )
1261+ try :
1262+ f_pred = acq_function .objective (mean )
1263+ # Some acquisition functions do not have an objective
1264+ # and for some acquisition functions the objective is None
1265+ except (AttributeError , TypeError ):
1266+ f_pred = mean
1267+ if hasattr (acq_function , "maximize" ):
1268+ # make sure that the optimiztaion direction is set properly
1269+ if not acq_function .maximize :
1270+ f_pred = - f_pred
1271+ try :
1272+ # handle constraints for EHVI-based acquisition functions
1273+ constraints = acq_function .constraints
1274+ if constraints is not None :
1275+ neg_violation = - torch .stack (
1276+ [c (mean ).clamp_min (0.0 ) for c in constraints ], dim = - 1
1277+ ).sum (dim = - 1 )
1278+ feas = neg_violation == 0
1279+ if feas .any ():
1280+ f_pred [~ feas ] = float ("-inf" )
1281+ else :
1282+ # set objective equal to negative violation
1283+ f_pred = neg_violation
1284+ except AttributeError :
1285+ pass
1286+ if f_pred .ndim == mean .ndim and f_pred .shape [- 1 ] > 1 :
1287+ # multi-objective
1288+ # find pareto set
1289+ is_pareto = is_non_dominated (f_pred )
1290+ best_X = X [is_pareto ]
1291+ else :
1292+ if f_pred .shape [- 1 ] == 1 :
1293+ f_pred = f_pred .squeeze (- 1 )
1294+ n_best = max (1 , round (X .shape [0 ] * best_pct / 100 ))
1295+ # the view() is to ensure that best_idcs is not a scalar tensor
1296+ best_idcs = torch .topk (f_pred , n_best ).indices .view (- 1 )
1297+ best_X = X [best_idcs ]
1298+
12111299 use_perturbed_sampling = best_X .shape [- 1 ] >= 20 or prob_perturb is not None
12121300 n_trunc_normal_points = (
12131301 n_discrete_points // 2 if use_perturbed_sampling else n_discrete_points
0 commit comments