response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Creates a constraint gp.
def _create_constrained_gp(features: np.ndarray, labels: np.ndarray): """Creates a constraint gp.""" # This logging is too chatty because paramz transformations do not implement # log jacobians. Silence it. logging.logging.getLogger('paramz.transformations').setLevel( logging.logging.CRITICAL) class L...
No-op. Marks functions that can be easily overridden for experimentation. Args: fun: Returns: fun:
def _experimental_override_allowed(fun): """No-op. Marks functions that can be easily overridden for experimentation. Args: fun: Returns: fun: """ return fun
Sets up a GP designer and outputs completed studies for `f`. Args: f: 1D objective to be optimized, i.e. f(x), where x is a scalar in [-5., 5.) num_trials: Number of mock "evaluated" trials to return. Returns: A GP designer set up for the problem of optimizing the objective, without any data updated. Evaluated tr...
def _setup_lambda_search( f: Callable[[float], float], num_trials: int = 100 ) -> tuple[gp_bandit.VizierGPBandit, list[vz.Trial], vz.ProblemStatement]: """Sets up a GP designer and outputs completed studies for `f`. Args: f: 1D objective to be optimized, i.e. f(x), where x is a scalar in [-5., 5.) num_...
Evaluate the designer's accuracy on the test set. Args: designer: The GP bandit designer to predict from. test_trials: The trials of the test set y_test: The results of the test set Returns: The MSE of `designer` on `test_trials` and `y_test`
def _compute_mse( designer: gp_bandit.VizierGPBandit, test_trials: list[vz.Trial], y_test: list[float], ) -> float: """Evaluate the designer's accuracy on the test set. Args: designer: The GP bandit designer to predict from. test_trials: The trials of the test set y_test: The results of the...
Returns True iff there are newer completed trials than active trials. Args: completed_trials: Completed trials. active_trials: Active trials. Returns: True if `completed_trials` is non-empty and: - `active_trials` is empty, or - The latest `completion_time` among `completed_trials` is later than t...
def _has_new_completed_trials( completed_trials: Sequence[vz.Trial], active_trials: Sequence[vz.Trial] ) -> bool: """Returns True iff there are newer completed trials than active trials. Args: completed_trials: Completed trials. active_trials: Active trials. Returns: True if `completed_trials` i...
Computes a threshold on UCB values. A promising evaluation point has UCB value no less than the threshold computed here. The threshold is the predicted mean of the feature array with the maximum UCB value among the points `gprm.index_points`. Args: gprm: A GP regression model for a set of predictive index points. ...
def _compute_ucb_threshold( gprm: tfd.Distribution, is_missing: jt.Bool[jt.Array, ''], ucb_coefficient: jt.Float[jt.Array, ''], ) -> jax.Array: """Computes a threshold on UCB values. A promising evaluation point has UCB value no less than the threshold computed here. The threshold is the predicted me...
Applies the trust region to acquisition function values. Args: tr: Trust region. xs: Predictive index points. acq_values: Acquisition function values at predictive index points. Returns: Acquisition function values with trust region applied.
def _apply_trust_region( tr: acquisitions.TrustRegion, xs: types.ModelInput, acq_values: jax.Array ) -> jax.Array: """Applies the trust region to acquisition function values. Args: tr: Trust region. xs: Predictive index points. acq_values: Acquisition function values at predictive index points. Ret...
Gets the shapes of continuous/categorical features for logging.
def _get_features_shape( features: types.ModelInput, ) -> types.ContinuousAndCategorical: """Gets the shapes of continuous/categorical features for logging.""" return types.ContinuousAndCategorical( features.continuous.shape, features.categorical.shape, )
Outputs all possible binary vectors from {-1, 1}^{dim} where only positions from `indices` are changed.
def _binary_subset_enumeration( dim: int, indices: Sequence[int], default_value: float = 1.0 ) -> np.ndarray: """Outputs all possible binary vectors from {-1, 1}^{dim} where only positions from `indices` are changed.""" output = default_value * np.ones( shape=(2 ** len(indices), dim), dtype=np.float32 )...
Factory for an Ensemble of Gaussian weighted scalarized Designers.
def create_gaussian_scalarizing_designer( problem_statement: vz.ProblemStatement, designer_factory: vza.DesignerFactory[vza.Designer], scalarization_factory: scalarization.ScalarizationFromWeights, num_ensemble: int, *, seed: Optional[int] = None, ) -> vza.Designer: """Factory for an Ensemble ...
Iterates over the search space parameters to find parameter by name.
def _get_parameter_config(search_space: vz.SearchSpace, param_name: str) -> Optional[vz.ParameterConfig]: """Iterates over the search space parameters to find parameter by name.""" for param_config in search_space.parameters: if param_config.name == param_name: return param_conf...
Tests that the pool size doesn't change when adding an infeasible fly.
def test_pool_size_with_infeasible(self): """Tests that the pool size doesn't change when adding an infeasible fly.""" firefly_pool = testing.create_fake_populated_firefly_pool( x_values=[1, 2, 5, -1], obj_values=[2, 10, -2, 8], capacity=5 ) infeasible_firefly_id = firefly_pool.generate_new_fly_id() inf...
Serialize parts of the FireflyPool.
def partially_serialize_firefly_pool(firefly_pool: FireflyPool) -> str: """Serialize parts of the FireflyPool.""" return json.dumps(firefly_pool, cls=PartialFireflyPoolEncoder)
Fully restore the FireflyPool.
def restore_firefly_pool(utils: EagleStrategyUtils, obj: str) -> FireflyPool: """Fully restore the FireflyPool.""" return FireflyPoolDecoder(utils).decode(obj)
Serialize Numpy Random Genertor.
def serialize_rng(rng: np.random.Generator) -> str: """Serialize Numpy Random Genertor.""" return json.dumps(rng.bit_generator.state)
Restore Numpy Random Genertor.
def restore_rng(obj: str) -> np.random.Generator: """Restore Numpy Random Genertor.""" rng = np.random.default_rng() rng.bit_generator.state = json.loads(obj) return rng
Create a fake completed trial ('obj_value' = None means infeasible trial).
def create_fake_trial( parent_fly_id: int, x_value: float, obj_value: Optional[float], ) -> vz.Trial: """Create a fake completed trial ('obj_value' = None means infeasible trial).""" trial = vz.Trial() measurement = vz.Measurement( metrics={ eagle_strategy_utils.OBJECTIVE_NAME: vz.Metr...
Create a fake problem statement.
def create_fake_problem_statement() -> vz.ProblemStatement: """Create a fake problem statement.""" problem = vz.ProblemStatement() problem.search_space.root.add_float_param('x', 0.0, 10.0) problem.metric_information.append( vz.MetricInformation( name=eagle_strategy_utils.OBJECTIVE_NAME, ...
Create a fake firefly with a fake completed trial.
def create_fake_fly( parent_fly_id: int, x_value: float, obj_value: Optional[float], ) -> Firefly: """Create a fake firefly with a fake completed trial.""" trial = create_fake_trial(parent_fly_id, x_value, obj_value) return Firefly(id_=parent_fly_id, perturbation=1.0, generation=1, trial=trial)
Create a fake empty Firefly pool.
def create_fake_empty_firefly_pool(capacity: int = 10) -> FireflyPool: """Create a fake empty Firefly pool.""" problem = create_fake_problem_statement() # By default incorporating infeasible trials is disabled; setting it manually. config = FireflyAlgorithmConfig(infeasible_force_factor=0.1) rng = np.random.d...
Create a fake populated Firefly pool with a given capacity.
def create_fake_populated_firefly_pool( *, capacity: int, x_values: Optional[list[float]] = None, obj_values: Optional[list[Optional[float]]] = None, parent_fly_ids: Optional[list[int]] = None, ) -> FireflyPool: """Create a fake populated Firefly pool with a given capacity.""" firefly_pool = cre...
Create a fake empty eagle designer.
def create_fake_empty_eagle_designer() -> EagleStrategyDesiger: """Create a fake empty eagle designer.""" problem = create_fake_problem_statement() return EagleStrategyDesiger(problem_statement=problem)
Create a fake populated eagle designer.
def create_fake_populated_eagle_designer( *, x_values: Optional[list[float]] = None, obj_values: Optional[list[Optional[float]]] = None, parent_fly_ids: Optional[list[int]] = None, ) -> EagleStrategyDesiger: """Create a fake populated eagle designer.""" problem = create_fake_problem_statement() ea...
Returns the maximum values of labels. A note on "labels" in TFP acquisition functions: TFP acquisition functions (EI, PI, qEI, qUCB) take the maximum of `"observations"` (labels) over the rightmost axis, which is assumed to correspond to the number of observations. `best_labels` has a (singleton) rightmost dimension c...
def get_best_labels(labels: types.PaddedArray) -> jax.Array: """Returns the maximum values of labels. A note on "labels" in TFP acquisition functions: TFP acquisition functions (EI, PI, qEI, qUCB) take the maximum of `"observations"` (labels) over the rightmost axis, which is assumed to correspond to the numbe...
Applies the trust region to acquisition values.
def _apply_trust_region( region: 'TrustRegion', xs: types.ModelInput, acquisition: jax.Array, pred: tfd.Distribution, aux: chex.ArrayTree, ) -> tuple[jax.Array, chex.ArrayTree]: """Applies the trust region to acquisition values.""" distance = region.min_linf_distance(xs) raw_acquisition = acqu...
Builds a ScoringFunctionFactory.
def bayesian_scoring_function_factory( acquisition_fn_factory: Callable[[types.ModelData], AcquisitionFunction], ) -> ScoringFunctionFactory: """Builds a ScoringFunctionFactory.""" def f( data: types.ModelData, predictive: Predictive, use_trust_region: bool = False, ) -> ScoreFunction: ...
Gets a GP model coroutine. Args: data: The data used to the train the GP model linear_coef: If non-zero, uses a linear kernel with `linear_coef` hyperparameter. Returns: The model coroutine.
def get_vizier_gp_coroutine( data: types.ModelData, *, linear_coef: float = 0.0, ) -> sp.ModelCoroutine: """Gets a GP model coroutine. Args: data: The data used to the train the GP model linear_coef: If non-zero, uses a linear kernel with `linear_coef` hyperparameter. Returns: The ...
Trains a Gaussian Process model. 1. Performs ARD to find the best model parameters. 2. Pre-computes the Cholesky decomposition for the model. Args: spec: Spec required to train the GP. See `GPTrainingSpec` for more info. data: Data on which to train the GP. Returns: The trained GP model.
def _train_gp(spec: GPTrainingSpec, data: types.ModelData) -> GPState: """Trains a Gaussian Process model. 1. Performs ARD to find the best model parameters. 2. Pre-computes the Cholesky decomposition for the model. Args: spec: Spec required to train the GP. See `GPTrainingSpec` for more info. data: D...
Returns the mean of the predictions from `pred` on `features`. Workaround while `eqx.filter_jit(pred.pred_with_aux)(features)` is broken due to a bug in tensorflow probability. Args: pred: `Predictive` to predict with. features: Xs to predict on. Returns: Means of the predictions from `pred` on `features`.
def _pred_mean( pred: acquisitions.Predictive, features: types.ModelInput ) -> types.Array: """Returns the mean of the predictions from `pred` on `features`. Workaround while `eqx.filter_jit(pred.pred_with_aux)(features)` is broken due to a bug in tensorflow probability. Args: pred: `Predictive` to pr...
Trains a `StackedResidualGP`. Completes the following steps in order: 1. Uses `base_gp` to predict on the `data` 2. Computes the residuals from the above predictions 3. Trains a top-level GP on the above residuals 4. Returns a `StackedResidualGP` combining the base GP and newly-trained GP. Args: base_gp: ...
def train_stacked_residual_gp( base_gp: GPState, spec: GPTrainingSpec, data: types.ModelData, ) -> StackedResidualGP: """Trains a `StackedResidualGP`. Completes the following steps in order: 1. Uses `base_gp` to predict on the `data` 2. Computes the residuals from the above predictions 3. T...
Trains a Gaussian Process model. If `spec` contains multiple elements, each will be used to train a `StackedResidualGP`, sequentially. The first entry will be used to train the first GP, and then subsequent GPs will be trained on the residuals from the previous GP. This process completes in the order that `spec` and `...
def train_gp( spec: Union[GPTrainingSpec, Iterable[GPTrainingSpec]], data: Union[types.ModelData, Iterable[types.ModelData]], ) -> GPState: """Trains a Gaussian Process model. If `spec` contains multiple elements, each will be used to train a `StackedResidualGP`, sequentially. The first entry will be use...
Sets up training state for a GP and outputs an test set for `f`. Args: f: 1D objective to be optimized, i.e. f(x), where x is a scalar in [-5., 5.) num_train: Number of training samples to generate. num_test: Number of testing samples to generate. linear_coef: If set, uses a linear kernel with coef `linear_coe...
def _setup_lambda_search( f: Callable[[float], float], num_train: int = 100, num_test: int = 100, linear_coef: float = 0.0, ensemble_size: int = 1, ) -> tuple[gp_models.GPTrainingSpec, types.ModelData, types.ModelData]: """Sets up training state for a GP and outputs an test set for `f`. Args: ...
Computes the mean-squared error of `predictive` on `test_data.
def _compute_mse( predictive: acquisitions.Predictive, test_data: types.ModelData ) -> float: """Computes the mean-squared error of `predictive` on `test_data.""" pred_dist, _ = predictive.predict_with_aux(test_data.features) # We need this reshape to prevent a broadcast from (num_samples, ) - # (num_samp...
Checks and modifies the shape and values of the labels.
def _validate_labels(labels_arr: types.Array) -> types.Array: """Checks and modifies the shape and values of the labels.""" labels_arr = labels_arr.astype(float) if not (labels_arr.ndim == 2 and labels_arr.shape[-1] == 1): raise ValueError( 'Labels need to be an array of shape (num_points, 1).' ...
Creates an output warper pipeline. Args: half_rank_warp: boolean indicating if half-rank warping to be performed. log_warp: boolean indicating if log warping to be performed. infeasible_warp: boolean indicating if infeasible warping to be performed. Returns: an instance of OutputWarperPipeline.
def create_default_warper( *, half_rank_warp: bool = True, log_warp: bool = True, infeasible_warp: bool = True, ) -> OutputWarperPipeline: """Creates an output warper pipeline. Args: half_rank_warp: boolean indicating if half-rank warping to be performed. log_warp: boolean indicating if log...
Creates an output warper outline which detects outliers and warps them.
def create_warp_outliers_warper( *, warp_outliers: bool = True, infeasible_warp: bool = True, transform_gaussian: bool = True, ) -> OutputWarperPipeline: """Creates an output warper outline which detects outliers and warps them.""" warpers = [] if warp_outliers: warpers.append(DetectOutliers()...
Computes the DOF of a `Predictive`. This is a maximum of two measures of DOF. The first represents the DOF associated with a log likelihood computation, after optimizing the hyperparameters of the kernel, i.e. the degrees-of-freedom (dof) of a finite linear regression problem. The second represents the fact we know ...
def _compute_dof(training_data_count: int, num_hyperparameters: int) -> float: """Computes the DOF of a `Predictive`. This is a maximum of two measures of DOF. The first represents the DOF associated with a log likelihood computation, after optimizing the hyperparameters of the kernel, i.e. the degrees-of-f...
Combines two predictions from transfer learning. The means are combined as a simple sum. The standard deviations are combined using a geometric mean, with a weighting coefficient `alpha` that sets their relative importance. See the below code for the exact computation of `alpha`, which is a function of the uncertain...
def combine_predictions_with_aux( top_pred: TransferPredictionState, base_pred: TransferPredictionState, *, expected_base_stddev_mismatch: float = 1.0 ) -> tuple[tfd.Distribution, chex.ArrayTree]: """Combines two predictions from transfer learning. The means are combined as a simple sum. The sta...
Returns the power transformation with optimal parameterization. The optimal parameterization makes the transformed data as "normal"-esque as possible. Args: data: 1-D or 2-D array. If 1-D, then the bijector has batch_shape =[]. If 2-D, then the bijector has batch shape equal to the last dimension method: 'yeo...
def optimal_transformation( data: np.ndarray, method: Literal['yeo-johnson', 'box-cox'] = 'yeo-johnson', *, standardize: bool = True) -> tfb.AutoCompositeTensorBijector: """Returns the power transformation with optimal parameterization. The optimal parameterization makes the transformed data as "no...
Returns the meta eagle search space.
def meta_eagle_search_space() -> vz.SearchSpace: """Returns the meta eagle search space.""" search_space = vz.SearchSpace() # Perturbation search_space.root.add_float_param( name='perturbation', min_value=1e-4, max_value=1e2, default_value=1e-1, scale_type=vz.ScaleType.LOG, ) s...
Creates an EagleStrategyDesigner with hyper-parameters and seed.
def _eagle_designer_factory( problem: vz.ProblemStatement, seed: Optional[int], **kwargs ): """Creates an EagleStrategyDesigner with hyper-parameters and seed.""" config = eagle_strategy.FireflyAlgorithmConfig() # Unpack the hyperparameters into the Eagle config class. for param_name, param_value in kwargs....
Creates an EagleStrategyDesigner with hyper-parameters and seed.
def _eagle_designer_factory( problem: vz.ProblemStatement, seed: Optional[int], **kwargs ): """Creates an EagleStrategyDesigner with hyper-parameters and seed.""" config = eagle_strategy.FireflyAlgorithmConfig() # Unpack the hyperparameters into the Eagle config class. for param_name, param_value in kwargs....
Creates a QuasiRandomDesigner with seed.
def _quasirandom_designer_factory( problem: vz.ProblemStatement, seed: Optional[int] = None ): """Creates a QuasiRandomDesigner with seed.""" return quasi_random.QuasiRandomDesigner(problem.search_space, seed=seed)
Compute softmax values for x.
def softmax(x: np.ndarray) -> np.ndarray: """Compute softmax values for x.""" e_x = np.exp(x - np.max(x)) return e_x / np.sum(e_x)
Pareto rank, which is the number of points dominating it. Args: ys: (number of population) x (number of metrics) array. Returns: (number of population) integer array.
def _pareto_rank(ys: np.ndarray) -> np.ndarray: """Pareto rank, which is the number of points dominating it. Args: ys: (number of population) x (number of metrics) array. Returns: (number of population) integer array. """ if ys.shape[0] == 0: return np.zeros([0]) dominated = [np.all(ys <= r, a...
Crowding distance. Args: ys: (number of population) x (number of metrics) array. Returns: (number of population) float32 array. Higher numbers mean less crowding and more desirable.
def _crowding_distance(ys: np.ndarray) -> np.ndarray: """Crowding distance. Args: ys: (number of population) x (number of metrics) array. Returns: (number of population) float32 array. Higher numbers mean less crowding and more desirable. """ scores = np.zeros([ys.shape[0]], dtype=np.float32) ...
Counts the constraints violated. Args: ys: (number of population) x (number of metrics) array. Returns: (number of population) array of integers.
def _constraint_violation(ys: np.ndarray) -> np.ndarray: """Counts the constraints violated. Args: ys: (number of population) x (number of metrics) array. Returns: (number of population) array of integers. """ return np.sum(ys < 0, axis=1)
Returns a boolean index array for the top `target` elements of ys. This method is tough to parse. Please improve the API if you see a better design! Args: ys: Array of shape [M]. Entries are expected to have a small set of unique values. target: Count to return. Returns: A tuple of two bolean index arrays ...
def _select_by(ys: np.ndarray, target: int) -> Tuple[np.ndarray, np.ndarray]: """Returns a boolean index array for the top `target` elements of ys. This method is tough to parse. Please improve the API if you see a better design! Args: ys: Array of shape [M]. Entries are expected to have a small set of un...
Choose objective and safety metrics and split. Args: metrics: Returns: Tuple of objective and safety metrics.
def _filter_and_split( metrics: Collection[vz.MetricInformation], ) -> Tuple[List[vz.MetricInformation], List[vz.MetricInformation]]: """Choose objective and safety metrics and split. Args: metrics: Returns: Tuple of objective and safety metrics. """ metrics_by_type = collections.defaultdict(lis...
Creates a shape validator for attr. For example, _shape_equals(lambda s : [3, None]) validates that the shape has length 2 and its first element is 3. Args: instance_to_shape: Takes instance as input and returns the desired shape for the instance. `None` is treated as "any number". Returns: A validator that ...
def _shape_equals( instance_to_shape: Callable[[Any], Collection[Optional[int]]] ): """Creates a shape validator for attr. For example, _shape_equals(lambda s : [3, None]) validates that the shape has length 2 and its first element is 3. Args: instance_to_shape: Takes instance as input and returns the...
Returns parameter converters.
def _create_parameter_converters( search_space: vz.SearchSpace, ) -> Collection[converters.DefaultModelInputConverter]: """Returns parameter converters.""" if search_space.is_conditional: raise ValueError('Cannot handle conditional search space!') def create_input_converter( pc: vz.ParameterConfig,...
Computes distance between features (or parallel feature batches).
def _compute_features_dist( x_batch: vb.VectorizedOptimizerInput, x_pool: vb.VectorizedOptimizerInput ) -> jax.Array: """Computes distance between features (or parallel feature batches).""" dist = jnp.zeros([], dtype=x_batch.continuous.dtype) if x_batch.continuous.size > 0: x_batch_cont = jnp.reshape( ...
Flips the ordering of the elements in `prior_rewards` and `prior_features`. Args: prior_features: Prior features to be flipped. prior_rewards: Prior rewards to be flipped. Returns: A tuple of flipped prior features and prior rewards such that all elements corresponding to -inf entries in `prior_rewards` are a...
def _mask_flip( prior_features: vb.VectorizedOptimizerInput, prior_rewards: types.Array ) -> Tuple[vb.VectorizedOptimizerInput, types.Array]: """Flips the ordering of the elements in `prior_rewards` and `prior_features`. Args: prior_features: Prior features to be flipped. prior_rewards: Prior rewards t...
A version of `_create_features` that materializes large intermediates.
def _create_features_simple( features, rewards, features_batch, rewards_batch, config, n_features, categorical_sizes, max_categorical_size, seed, ): """A version of `_create_features` that materializes large intermediates.""" # Only works with no parallel batch dimension. conti...
Creates a new vectorized strategy based on the Protocol.
def random_strategy_factory( converter: converters.TrialToModelInputConverter, suggestion_batch_size: int, ) -> vb.VectorizedStrategy: """Creates a new vectorized strategy based on the Protocol.""" return RandomVectorizedStrategy( converter=converter, suggestion_batch_size=suggestion_batch_size,...
Creates a random optimizer.
def create_random_optimizer( converter: converters.TrialToModelInputConverter, max_evaluations: int, suggestion_batch_size: int, ) -> vb.VectorizedOptimizer: """Creates a random optimizer.""" return vb.VectorizedOptimizerFactory( strategy_factory=random_strategy_factory, max_evaluations=max_...
Creates a random optimizer factory.
def create_random_optimizer_factory( max_evaluations: int, suggestion_batch_size: int ) -> vb.VectorizedOptimizerFactory: """Creates a random optimizer factory.""" return vb.VectorizedOptimizerFactory( strategy_factory=random_strategy_factory, max_evaluations=max_evaluations, suggestion_batch_...
Docstring.
def _reshape_to_parallel_batches( x: types.PaddedArray, parallel_dim: int ) -> tuple[jax.Array, jax.Array]: """Docstring.""" new_batch_dim = x.shape[0] // parallel_dim new_padded_array = jnp.reshape( x.padded_array[: new_batch_dim * parallel_dim], (new_batch_dim, parallel_dim, x.shape[-1]), ) ...
Returns the best candidate trials in the original search space.
def best_candidates_to_trials( best_results: VectorizedStrategyResults, converter: converters.TrialToModelInputConverter, ) -> list[vz.Trial]: """Returns the best candidate trials in the original search space.""" best_features = best_results.features trials = [] sorted_ind = jnp.argsort(-best_results.re...
Sorts trials by the order they were created and converts to array.
def trials_to_sorted_array( prior_trials: list[vz.Trial], converter: converters.TrialToModelInputConverter, ) -> Optional[types.ModelInput]: """Sorts trials by the order they were created and converts to array.""" if prior_trials: prior_trials = sorted(prior_trials, key=lambda x: x.creation_time) pr...
Creates the default runner with completed and active trials.
def _create_runner() -> pythia.InRamPolicySupporter: """Creates the default runner with completed and active trials.""" runner = pythia.InRamPolicySupporter(vz.ProblemStatement()) runner.AddTrials( [ vz.Trial().complete(vz.Measurement()) for _ in range(_NUM_INITIAL_COMPLETED_TRIALS) ...
Samples unifrom value and udpate key.
def sample_uniform(rng: np.random.Generator, min_value=0, max_value=1) -> float: """Samples unifrom value and udpate key.""" return float(rng.uniform(low=min_value, high=max_value))
Samples value1 with probability prob1.
def sample_bernoulli( rng: np.random.Generator, prob1: float, value1: _T = 0, value2: _T = 1, ) -> _T: """Samples value1 with probability prob1.""" return value1 if rng.binomial(1, p=prob1) else value2
Samples a random integer.
def sample_integer( rng: np.random.Generator, min_value: float, max_value: float, ) -> int: """Samples a random integer.""" val = sample_uniform(rng, min_value, max_value) return round(val)
Samples a random categorical value.
def sample_categorical(rng: np.random.Generator, categories: List[str]) -> str: """Samples a random categorical value.""" return rng.choice(categories)
Samples random discrete value. To sample a discrete value we sample uniformly a decimal value between the minimum and maximum feasible points and returns the closest feasible point. Args: rng: feasible_points: Returns: The sampled feasible point and a new key.
def sample_discrete(rng: np.random.Generator, feasible_points: List[float]) -> float: """Samples random discrete value. To sample a discrete value we sample uniformly a decimal value between the minimum and maximum feasible points and returns the closest feasible point. Args: rng: ...
Finds closest element in array to value.
def get_closest_element(array: List[float], value: float) -> float: """Finds closest element in array to value.""" gaps = [abs(x - value) for x in array] closest_idx = min(enumerate(gaps), key=lambda x: x[1])[0] return array[closest_idx]
Samples random value based on the parameter type.
def _sample_value( rng: np.random.Generator, param_config: vz.ParameterConfig, ) -> vz.ParameterValueTypes: """Samples random value based on the parameter type.""" if param_config.type == vz.ParameterType.CATEGORICAL: return sample_categorical(rng, param_config.feasible_values) elif param_config.type ...
Randomly samples parameter values from the search space.
def sample_parameters(rng: np.random.Generator, search_space: vz.SearchSpace) -> vz.ParameterDict: """Randomly samples parameter values from the search space.""" sampled_parameters: Dict[str, vz.ParameterValue] = {} parameter_configs: List[vz.ParameterConfig] = search_space.parameters for...
Create a new list of shuffled items. Original list remains the same.
def shuffle_list(rng: np.random.Generator, items: List[_T]) -> List[_T]: """Create a new list of shuffled items. Original list remains the same.""" shuffled_indices = np.array(range(len(items))) rng.shuffle(shuffled_indices) shuffled_items = [items[i] for i in shuffled_indices] return shuffled_items
Generates an interpolation function from a trial's measurement data. Since different trials have evaluations at different step numbers, we need to be able to interpolate the objective value between steps in order to compare trials and regress against trial data. This function converts a trial into a function suitable ...
def _generate_interpolation_fn_from_trial( steps: list[int], values: list[float] ) -> Callable[[int], float]: """Generates an interpolation function from a trial's measurement data. Since different trials have evaluations at different step numbers, we need to be able to interpolate the objective value betwee...
Sort and remove duplicates in the trial's measurements. Args: steps: a list of integer measurement steps for a given trial. values: a list of objective values corresponding to the steps for a given trial. Returns: steps: a list of integer measurement steps after dedupe. values: a list of objective values ...
def _sort_dedupe_measurements( steps: list[Union[int, float]], values: list[float] ) -> Tuple[list[Union[int, float]], list[float]]: """Sort and remove duplicates in the trial's measurements. Args: steps: a list of integer measurement steps for a given trial. values: a list of objective values correspo...
Smoke test on random score.
def assert_passes_on_random_single_metric_function( self, search_space: vz.SearchSpace, optimizer: vza.GradientFreeOptimizer, *, np_random_seed: int): """Smoke test on random score.""" rng = np.random.default_rng(np_random_seed) logging.info('search space: %s', search_space) problem = vz.ProblemStatem...
Bi-objective test on random score.
def assert_passes_on_random_multi_metric_function( self, search_space: vz.SearchSpace, optimizer: vza.GradientFreeOptimizer, *, np_random_seed: int ): """Bi-objective test on random score.""" rng = np.random.default_rng(np_random_seed) logging.info('search space: %s', search_space) problem...
DO NOT USE. DEPRECATED. Use RandomMetricsRunner.run_designer().
def run_with_random_metrics( designer: vza.Designer, problem: vz.ProblemStatement, iters: int = 5, *, batch_size: Optional[int] = 1, seed: Any = None, verbose: int = 0, validate_parameters: bool = False, ) -> Sequence[vz.Trial]: """DO NOT USE. DEPRECATED. Use RandomMetricsRunner.ru...
Builds a relative convergence curve (see returns for definition). Finds the smallest index j for each element i in 'baseline_curve' such that baseline_curve[i] <= compared_curve[j]. The function uses the 'bisect_left' function to efficiently perform binary search under the assumption that 'baseline_curve' and 'compare...
def build_convergence_curve( baseline_curve: Sequence[float], compared_curve: Sequence[float] ) -> List[float]: """Builds a relative convergence curve (see returns for definition). Finds the smallest index j for each element i in 'baseline_curve' such that baseline_curve[i] <= compared_curve[j]. The function...
Returns trials where trials[i] has empty metric name equal to values[i].
def _gen_trials(values): """Returns trials where trials[i] has empty metric name equal to values[i].""" trials = [] for v in values: trial = pyvizier.Trial() trials.append( trial.complete( pyvizier.Measurement(metrics={'': pyvizier.Metric(value=v)}))) return trials
Computes the entropy of parameter values. Args: parameter_config: The parameter config. parameter_values: Values of a parameter. WARNING: Entropy estimation accuracy depends on the sample size, so to compare the entropies of two `parameter_values`, make sure they have the same size. Returns: The entropy of par...
def compute_parameter_entropy( parameter_config: vz.ParameterConfig, parameter_values: Iterable[Optional[vz.ParameterValue]], ) -> float: """Computes the entropy of parameter values. Args: parameter_config: The parameter config. parameter_values: Values of a parameter. WARNING: Entropy estimatio...
Computes the average marginal parameter entropy across results. Computes the marginal entropy of every parameter in every study, and then returns the average marginal entropy over all parameters and all studies. Args: results: Benchmark results. Returns: Average marginal parameter entropy.
def compute_average_marginal_parameter_entropy( results: BenchmarkResults, ) -> float: """Computes the average marginal parameter entropy across results. Computes the marginal entropy of every parameter in every study, and then returns the average marginal entropy over all parameters and all studies. Args...
Generates two studies with zero and large parameter entropies.
def _generate_min_and_max_ent_studies() -> ( Tuple[vz.ProblemAndTrials, vz.ProblemAndTrials] ): """Generates two studies with zero and large parameter entropies.""" space = vz.SearchSpace() root = space.root root.add_float_param('continuous', -5.0, 5.0) root.add_int_param('integer', -5, 5) root.add_cate...
Aggregates multiple convergence curves into a plot with confidence bounds. Example usage: ```python fig, ax = plt.subplots(1, 1, figsize=(12,8)) plot_median_convergence(ax, [[1,1,2,3,4], [1,1,1,2,nan]], percentiles=((40, 60), (30, 70)), ...
def plot_median_convergence( ax: mpl.axes.Axes, curves: 'np.ndarray', *, percentiles: Sequence[Tuple[int, int]] = ((40, 60),), alphas: Sequence[float] = (0.2,), xs: Optional['np.ndarray'] = None, **kwargs, ): """Aggregates multiple convergence curves into a plot with confidence bounds. ...
Aggregates multiple convergence curves into a plot with standard error bounds. Example usage: ```python fig, ax = plt.subplots(1, 1, figsize=(12,8)) plot_mean_convergence(ax, [[1,1,2,3,4], [1,1,1,2,nan]], alpha=0.3, xs=np.arange(1,6), ...
def plot_mean_convergence( ax: mpl.axes.Axes, curves: 'np.ndarray', *, alpha: float = 0.2, xs: Optional['np.ndarray'] = None, **kwargs, ): """Aggregates multiple convergence curves into a plot with standard error bounds. Example usage: ```python fig, ax = plt.subplots(1, 1, figsize=...
Generates a grid of algorithm comparison plots. Generates one plot for each Experimenter x Metrics in records. Note that each row = Experimenter and each column = Metrics. Args: records: All BenchmarkRecords used for plotting. metrics: Keys in the plot_elements dict in BenchmarkRecord used for plot. If not su...
def plot_from_records( records: Sequence[state_analyzer.BenchmarkRecord], metrics: Optional[Sequence[str]] = None, *, fig_title: str = 'All Plot Elements', title_maxlen: int = 50, col_figsize: float = 6.0, row_figsize: float = 6.0, **kwargs, ): """Generates a grid of algorithm comparis...
Computes the one-sided T-test score. In case of a maximization (minimizatoin) problem, it scores the confidence that the mean of 'baseline_mean_values' is less (greater) than the mean of 'candidate_mean_values'. The lower the score the higher the confidence that it's the case. One-sample ---------- The test assumes ...
def t_test_mean_score(baseline_mean_values: Union[list[float], np.ndarray], candidate_mean_values: Union[list[float], np.ndarray], objective_goal: vz.ObjectiveMetricGoal) -> float: """Computes the one-sided T-test score. In case of a maximization (minimizatoin) problem, ...
Helper function for creating full rainbow-based Atari 100k agent.
def create_agent_fn( sess, # pylint: disable=unused-argument environment, seed: Optional[int] = None, summary_writer=None) -> atari_100k_rainbow_agent.Atari100kRainbowAgent: """Helper function for creating full rainbow-based Atari 100k agent.""" return atari_100k_rainbow_agent.Atari100kRainbowAgent...
Produces a reasonable SearchSpace for tuning the Rainbow training process.
def default_search_space() -> pyvizier.SearchSpace: """Produces a reasonable SearchSpace for tuning the Rainbow training process.""" ss = pyvizier.SearchSpace() ss.root.add_float_param( 'JaxDQNAgent.gamma', 0.7, 0.999999, scale_type=pyvizier.ScaleType.REVERSE_LOG) ss.root.add_int_param('...
Surrogate function bounds.
def _surrogate_bounds(handler: handler_lib.HPOBHandler, search_space_id: str, dataset_id: str) -> Tuple[float, float]: """Surrogate function bounds.""" surrogate_name = 'surrogate-' + search_space_id + '-' + dataset_id y_min = handler.surrogates_stats[surrogate_name]['y_min'] y_max = handl...
Generates all test cases. Must be called after InitGoogle().
def generate_test_class(): """Generates all test cases. Must be called after InitGoogle().""" handler = handler_lib.HPOBHandler( root_dir=hpob_experimenter.ROOT_DIR, mode=hpob_experimenter.DEFAULT_TEST_MODE, surrogates_dir=hpob_experimenter.SURROGATES_DIR) class HpobTest(parameterized.TestCase...
Converts ops and nodes to a string format recognized by NASBENCH-201.
def _model_tss_spc(ops: Sequence[str], num_nodes: int) -> str: """Converts ops and nodes to a string format recognized by NASBENCH-201.""" nodes, k = [], 0 for i in range(1, num_nodes): xstrs = [] for j in range(i): xstrs.append('{:}~{:}'.format(ops[k], j)) k += 1 nodes.append('|' + '|'.j...
Creates a noise function via NumPy. See https://bee22.com/resources/bbob%20noisy%20functions.pdf Args: noise: Noise specification dimension: Dimensionality of bbob function that the noise is applied to. target_value: The noise does not apply to values less than this. seed: Returns: Callable that returns th...
def _create_noise_fn( noise: str, dimension: int, target_value: float = 1e-8, seed: Optional[int] = None, ) -> Callable[[float], float]: """Creates a noise function via NumPy. See https://bee22.com/resources/bbob%20noisy%20functions.pdf Args: noise: Noise specification dimension: Dimensi...
Uniform noise model for bbob-noisy benchmark. The noise strength increases when value is small. Args: value: Function value to apply noise to. amplifying_exponent: "alpha" in the paper. The higher this number is, the more likely it is for the noisy value to be greater than the input value. 0 or less means...
def _uniform_noise( value: float, amplifying_exponent: float, shrinking_exponent: float, rng: np.random.Generator, epsilon: float = 1e-99, ) -> float: """Uniform noise model for bbob-noisy benchmark. The noise strength increases when value is small. Args: value: Function value to apply n...
Additive normal noise.
def _additive_normal_noise( value: float, stddev: float, rng: np.random.Generator ) -> float: """Additive normal noise.""" return value + rng.normal(0.0, stddev)
Cauchy noise model for bbob-noisy benchmark. The noise is infrequent and difficult to analyze due to large outliers. Args: value: Function value to apply noise to. noise_strength: "alpha" in the paper. Its absolute value determines the noise strength. The recommended setup as in the paper is to use a positive...
def _cauchy_noise( value: float, noise_strength: float, noise_frequency: float, rng: np.random.Generator, ) -> float: """Cauchy noise model for bbob-noisy benchmark. The noise is infrequent and difficult to analyze due to large outliers. Args: value: Function value to apply noise to. noi...
Post processing of noise for bbob-noisy benchmark. We do not apply noise if the value is close to the global optima. This keeps the optimal value intact. Args: value: Function value to apply noise to. noisy_fn: "f_XX" in the paper. It applies noise to the input. target_value: If value is less than this number,...
def _stabilized_noise(value: float, noisy_fn: Callable[[float], float], target_value: float = 1e-8) -> float: """Post processing of noise for bbob-noisy benchmark. We do not apply noise if the value is close to the global optima. This keeps the optimal value intact. ...
Gets the name of underlying objects.
def _get_name(f): """Gets the name of underlying objects.""" if hasattr(f, '__name__'): return f.__name__ # Next clause handles functools.partial objects. if hasattr(f, 'func') and hasattr(f.func, '__name__'): return f.func.__name__ return repr(f)
Returns default BBOB ProblemStatement for given dimension.
def DefaultBBOBProblemStatement( dimension: int, *, metric_name="bbob_eval", min_value: float = -5.0, max_value: float = 5.0, scale_type=None, ) -> pyvizier.ProblemStatement: """Returns default BBOB ProblemStatement for given dimension.""" problem_statement = pyvizier.ProblemStatement() sp...
The BBOB LambdaAlpha matrix creation function. Args: alpha: Function parameter. dim: Dimension of matrix created. Returns: Diagonal matrix of dimension dim with values determined by alpha.
def LambdaAlpha(alpha: float, dim: int) -> np.ndarray: """The BBOB LambdaAlpha matrix creation function. Args: alpha: Function parameter. dim: Dimension of matrix created. Returns: Diagonal matrix of dimension dim with values determined by alpha. """ lambda_alpha = np.zeros([dim, dim]) for i i...
Create a new array by mapping fn() to each element of the original array. Args: vector: ndarray to be mapped. fn: scalar function for mapping. Returns: New ndarray be values mapped by fn.
def ArrayMap(vector: np.ndarray, fn: Callable[[float], float]) -> np.ndarray: """Create a new array by mapping fn() to each element of the original array. Args: vector: ndarray to be mapped. fn: scalar function for mapping. Returns: New ndarray be values mapped by fn. """ results = np.zeros(vect...
The BBOB T_osz function. Args: element: float input. Returns: Tosz(input).
def Tosz(element: float) -> float: """The BBOB T_osz function. Args: element: float input. Returns: Tosz(input). """ x_carat = 0.0 if element == 0 else math.log(abs(element)) c1 = 10.0 if element > 0 else 5.5 c2 = 7.9 if element > 0 else 3.1 return np.sign(element) * math.exp( x_carat + ...
The BBOB Tasy function. Args: vector: ndarray beta: Function parameter Returns: ndarray with values determined by beta.
def Tasy(vector: np.ndarray, beta: float) -> np.ndarray: """The BBOB Tasy function. Args: vector: ndarray beta: Function parameter Returns: ndarray with values determined by beta. """ dim = len(vector) result = np.zeros([dim, 1]) for i, val in enumerate(vector.flat): if val > 0: t...