response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Calculate the BBOB s_i.
Assumes i is 0-index based.
Args:
dim: dimension
to_sz: values
Returns:
float representing SIndex(i, d, to_sz). | def SIndex(dim: int, to_sz) -> float:
"""Calculate the BBOB s_i.
Assumes i is 0-index based.
Args:
dim: dimension
to_sz: values
Returns:
float representing SIndex(i, d, to_sz).
"""
s = np.zeros([
dim,
])
for i in range(dim):
if dim > 1:
s[i] = 10**(0.5 * (i / (dim - 1.0))... |
The BBOB Fpen function.
Args:
vector: ndarray.
Returns:
float representing Fpen(vector). | def Fpen(vector: np.ndarray) -> float:
"""The BBOB Fpen function.
Args:
vector: ndarray.
Returns:
float representing Fpen(vector).
"""
return sum([max(0.0, (abs(x) - 5.0))**2 for x in vector.flat]) |
Array of integers that can be used as random state seed. | def _IntSeeds(any_seeds: Sequence[Any], *, byte_length: int = 4) -> list[int]:
"""Array of integers that can be used as random state seed."""
int_seeds = []
for s in any_seeds:
# Encode into 4 byte_length worth of a hexadecimal string.
hashed = hashlib.shake_128(str(s).encode("utf-8")).hexdigest(byte_leng... |
Convert a%b where b is an int into a float on [-0.5, 0.5]. | def _ToFloat(a: int, b: np.ndarray) -> np.ndarray:
"""Convert a%b where b is an int into a float on [-0.5, 0.5]."""
return (np.int64(a) % b) / np.float64(b) - 0.5 |
Returns an orthonormal rotation matrix.
Args:
dim: size of the resulting matrix.
seed: int seed. If set to 0, this function returns an identity matrix
regardless of *moreseeds.
*moreseeds: Additional parameters to include in the hash. Arguments are
converted to strings first.
Returns:
Array of shape (... | def _R(dim: int, seed: int, *moreseeds: Any) -> np.ndarray:
"""Returns an orthonormal rotation matrix.
Args:
dim: size of the resulting matrix.
seed: int seed. If set to 0, this function returns an identity matrix
regardless of *moreseeds.
*moreseeds: Additional parameters to include in the hash.... |
Implementation for BBOB Sphere function. | def Sphere(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Sphere function."""
del seed
return float(np.sum(arr * arr)) |
Implementation for BBOB Rastrigin function. | def Rastrigin(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Rastrigin function."""
dim = len(arr)
arr.shape = (dim, 1)
z = np.matmul(_R(dim, seed, b"R"), arr)
z = Tasy(ArrayMap(z, Tosz), 0.2)
z = np.matmul(_R(dim, seed, b"Q"), z)
z = np.matmul(LambdaAlpha(10.0, dim), z)
z = np.mat... |
Implementation for BBOB BuecheRastrigin function. | def BuecheRastrigin(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB BuecheRastrigin function."""
del seed
dim = len(arr)
arr.shape = (dim, 1)
t = ArrayMap(arr, Tosz)
l = SIndex(dim, arr) * t.flat
term1 = 10 * (dim - np.sum(np.cos(2 * math.pi * l), axis=0))
term2 = np.sum(l * l, axi... |
Implementation for BBOB LinearSlope function. | def LinearSlope(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB LinearSlope function."""
dim = len(arr)
arr.shape = (dim, 1)
r = _R(dim, seed, b"R")
z = np.matmul(r, arr)
result = 0.0
for i in range(dim):
s = 10**(i / float(dim - 1) if dim > 1 else 1)
z_opt = 5 * np.sum(np.abs... |
Implementation for BBOB Attractive Sector function. | def AttractiveSector(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Attractive Sector function."""
dim = len(arr)
arr.shape = (dim, 1)
x_opt = np.array([1 if i % 2 == 0 else -1 for i in range(dim)])
x_opt.shape = (dim, 1)
z_vec = np.matmul(_R(dim, seed, b"R"), arr - x_opt)
z_vec = np... |
Implementation for BBOB StepEllipsoidal function. | def StepEllipsoidal(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB StepEllipsoidal function."""
dim = len(arr)
arr.shape = (dim, 1)
z_hat = np.matmul(_R(dim, seed, b"R"), arr)
z_hat = np.matmul(LambdaAlpha(10.0, dim), z_hat)
z_tilde = np.array([
math.floor(0.5 + z) if (z > 0.5) e... |
Implementation for BBOB RosenbrockRotated function. | def RosenbrockRotated(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB RosenbrockRotated function."""
dim = len(arr)
r_x = np.matmul(_R(dim, seed, b"R"), arr)
z = max(1.0, (dim**0.5) / 8.0) * r_x + 0.5 * np.ones((dim,))
return float(
sum([
100.0 * (z[i]**2 - z[i + 1])**2 + ... |
Implementation for BBOB Ellipsoidal function. | def Ellipsoidal(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Ellipsoidal function."""
del seed
dim = len(arr)
arr.shape = (dim, 1)
z_vec = ArrayMap(arr, Tosz)
s = 0.0
for i in range(dim):
exp = 6.0 * i / (dim - 1) if dim > 1 else 6.0
s += float(10**exp * z_vec[i] * z_vec[i]... |
Implementation for BBOB Discus function. | def Discus(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Discus function."""
dim = len(arr)
arr.shape = (dim, 1)
r_x = np.matmul(_R(dim, seed, b"R"), arr)
z_vec = ArrayMap(r_x, Tosz)
return float(10**6 * z_vec[0] * z_vec[0]) + sum(
[z * z for z in z_vec[1:].flat]) |
Implementation for BBOB BentCigar function. | def BentCigar(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB BentCigar function."""
dim = len(arr)
arr.shape = (dim, 1)
z_vec = np.matmul(_R(dim, seed, b"R"), arr)
z_vec = Tasy(z_vec, 0.5)
z_vec = np.matmul(_R(dim, seed, b"R"), z_vec)
return float(z_vec[0]**2) + 10**6 * np.sum(z_vec[... |
Implementation for BBOB SharpRidge function. | def SharpRidge(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB SharpRidge function."""
dim = len(arr)
arr.shape = (dim, 1)
z_vec = np.matmul(_R(dim, seed, b"R"), arr)
z_vec = np.matmul(LambdaAlpha(10, dim), z_vec)
z_vec = np.matmul(_R(dim, seed, b"Q"), z_vec)
return z_vec[0, 0]**2 + 1... |
Implementation for BBOB DifferentPowers function. | def DifferentPowers(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB DifferentPowers function."""
dim = len(arr)
z = np.matmul(_R(dim, seed, b"R"), arr)
s = 0.0
for i in range(dim):
exp = 2 + 4 * i / (dim - 1) if dim > 1 else 6
s += abs(z[i])**exp
return s**0.5 |
Implementation for BBOB Weierstrass function. | def Weierstrass(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Weierstrass function."""
k_order = 12
dim = len(arr)
arr.shape = (dim, 1)
z = np.matmul(_R(dim, seed, b"R"), arr)
z = ArrayMap(z, Tosz)
z = np.matmul(_R(dim, seed, b"Q"), z)
z = np.matmul(LambdaAlpha(1.0 / 100.0, dim), ... |
Implementation for BBOB Weierstrass function. | def SchaffersF7(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Weierstrass function."""
dim = len(arr)
arr.shape = (dim, 1)
if dim == 1:
return 0.0
z = np.matmul(_R(dim, seed, b"R"), arr)
z = Tasy(z, 0.5)
z = np.matmul(_R(dim, seed, b"Q"), z)
z = np.matmul(LambdaAlpha(10.0, dim... |
Implementation for BBOB SchaffersF7 Ill Conditioned. | def SchaffersF7IllConditioned(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB SchaffersF7 Ill Conditioned."""
dim = len(arr)
arr.shape = (dim, 1)
if dim == 1:
return 0.0
z = np.matmul(_R(dim, seed, b"R"), arr)
z = Tasy(z, 0.5)
z = np.matmul(_R(dim, seed, b"Q"), z)
z = np.matmul(... |
Implementation for BBOB GriewankRosenbrock function. | def GriewankRosenbrock(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB GriewankRosenbrock function."""
dim = len(arr)
r_x = np.matmul(_R(dim, seed, b"R"), arr)
# Slightly off BBOB documentation in order to center optima at origin.
# Should be: max(1.0, (dim**0.5) / 8.0) * r_x + 0.5 * np.o... |
Implementation for BBOB Schwefel function. | def Schwefel(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Schwefel function."""
del seed
dim = len(arr)
bernoulli_arr = np.array([pow(-1, i + 1) for i in range(dim)])
x_opt = 4.2096874633 / 2.0 * bernoulli_arr
x_hat = 2.0 * (bernoulli_arr * arr) # Element-wise multiplication
z_ha... |
Implementation for BBOB Katsuura function. | def Katsuura(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Katsuura function."""
dim = len(arr)
arr.shape = (dim, 1)
r_x = np.matmul(_R(dim, seed, b"R"), arr)
z_vec = np.matmul(LambdaAlpha(100.0, dim), r_x)
z_vec = np.matmul(_R(dim, seed, b"Q"), z_vec)
prod = 1.0
for i in range(d... |
Implementation for BBOB Lunacek function. | def Lunacek(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Lunacek function."""
dim = len(arr)
arr.shape = (dim, 1)
mu0 = 2.5
s = 1.0 - 1.0 / (2.0 * (dim + 20.0)**0.5 - 8.2)
mu1 = -((mu0**2 - 1) / s)**0.5
x_opt = np.array([mu0 / 2] * dim)
x_hat = np.array([2 * arr[i, 0] * np.sign(... |
Implementation for BBOB Gallagher101 function. | def Gallagher101Me(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Gallagher101 function."""
dim = len(arr)
arr.shape = (dim, 1)
num_optima = 101
optima_list = [np.zeros([dim, 1])]
for i in range(num_optima - 1):
vec = np.zeros([dim, 1])
for j in range(dim):
alpha = (i *... |
Implementation for BBOB Gallagher21 function. | def Gallagher21Me(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Gallagher21 function."""
dim = len(arr)
arr.shape = (dim, 1)
num_optima = 21
optima_list = [np.zeros([dim, 1])]
for i in range(num_optima - 1):
vec = np.zeros([dim, 1])
for j in range(dim):
alpha = (i * di... |
Implementation for BBOB Sphere function. | def NegativeSphere(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Sphere function."""
dim = len(arr)
arr.shape = (dim, 1)
z = np.matmul(_R(dim, seed, b"R"), arr)
return float(100 + np.sum(z * z) - 2 * (z[0]**2)) |
Implementation for NegativeMinDifference function. | def NegativeMinDifference(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for NegativeMinDifference function."""
dim = len(arr)
arr.shape = (dim, 1)
z = np.matmul(_R(dim, seed, b"R"), arr)
min_difference = 10000
for i in range(len(z) - 1):
min_difference = min(min_difference, z[i + 1] - z[i]... |
Implementation for FonsecaFleming function. | def FonsecaFleming(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for FonsecaFleming function."""
del seed
return 1.0 - float(np.exp(-np.sum(arr * arr))) |
Branin function.
This function can accept batch shapes, although it is typed to return floats
to conform to NumpyExperimenter API.
Args:
x: Shape (B*, 2) array.
Returns:
Shape (B*) array. | def _branin(x: np.ndarray) -> float:
"""Branin function.
This function can accept batch shapes, although it is typed to return floats
to conform to NumpyExperimenter API.
Args:
x: Shape (B*, 2) array.
Returns:
Shape (B*) array.
"""
a = 1
b = 5.1 / (4 * np.pi**2)
c = 5 / np.pi
r = 6
s = ... |
Computes the float term on a list of values.
Args:
x_list: Elements in the list correspond to a different dimension/Parameter.
Returns:
The float term accounting for all the float Parameters. | def _float_term(x_list: list[float]) -> float:
"""Computes the float term on a list of values.
Args:
x_list: Elements in the list correspond to a different dimension/Parameter.
Returns:
The float term accounting for all the float Parameters.
"""
float_term = 0
for x in x_list:
float_term += mi... |
Computes the categorical term. | def _categorical_term(x: str, best_category: SimpleKDCategory) -> float:
"""Computes the categorical term."""
if x != best_category:
return 0
elif x == 'corner':
return 1
elif x == 'center':
return 1
elif x == 'mixed':
return 1.5
raise NotImplementedError(f'Unknown categorical parameter: {x}... |
Computes the discrete term on a list of values. | def _discrete_term(x_list: list[int]) -> float:
"""Computes the discrete term on a list of values."""
discrete_term = 0
for x in x_list:
discrete_term += [1.2, 0.0, 0.6, 0.8, 1.0][
_feasible_discrete_values.index(x)
]
return discrete_term |
Computes the int term on a list of values. | def _int_term(x_list: list[int]) -> float:
"""Computes the int term on a list of values."""
int_term = 0
for x in x_list:
int_term += np.power(x - 2.2, 2) / 2.0
return int_term |
Asserts that random suggestions from the search space are valid. | def assert_evaluates_random_suggestions(
test,
experimenter: experimenter_lib.Experimenter,
) -> None:
"""Asserts that random suggestions from the search space are valid."""
runner = benchmark_runner.BenchmarkRunner(
[benchmark_runner.GenerateAndEvaluate(10)], num_repeats=1
)
state = benchmark_st... |
Loss function for a stochastic process model. | def stochastic_process_model_loss_fn(
params: types.ParameterDict,
model: sp.StochasticProcessModel,
data: types.ModelData,
normalize: bool = False,
):
"""Loss function for a stochastic process model."""
gp, mutables = model.apply(
{'params': params},
data.features,
mutable=['losse... |
Setup function for a stochastic process model. | def stochastic_process_model_setup(
key: jax.Array,
model: sp.StochasticProcessModel,
data: types.ModelData,
):
"""Setup function for a stochastic process model."""
return model.init(key, data.features)['params'] |
Generates the predictive distribution on array function. | def _build_predictive_distribution(
xs: types.ModelInput,
model: sp.StochasticProcessModel,
state: types.GPState,
use_vmap: bool = True,
) -> tfd.Distribution:
"""Generates the predictive distribution on array function."""
def _predict_on_array_one_model(
model_state: types.ModelState, *, xs:... |
Prediction function on features array. | def predict_on_array(
xs: types.ModelInput,
model: sp.StochasticProcessModel,
state: types.GPState,
use_vmap: bool = True,
):
"""Prediction function on features array."""
dist = _build_predictive_distribution(xs, model, state, use_vmap)
return {'mean': dist.mean(), 'stddev': dist.stddev()} |
Acquisition function on features array. | def acquisition_on_array(
xs: types.ModelInput,
model: sp.StochasticProcessModel,
acquisition_fn: acquisitions_lib.AcquisitionFunction,
state: types.GPState,
trust_region: Optional[acquisitions_lib.TrustRegion] = None,
use_vmap: bool = True,
):
"""Acquisition function on features array."""
d... |
Squeezes the singleton `metrics` dimension from `labels`, if applicable. | def _squeeze_to_event_dims(
dist: tfd.Distribution, labels: jax.Array
) -> jax.Array:
"""Squeezes the singleton `metrics` dimension from `labels`, if applicable."""
if len(dist.event_shape) == 1 and labels.shape == (dist.event_shape[0], 1):
return jnp.squeeze(labels, axis=-1)
return labels |
Gets the parameter constraints from a StochasticProcessModel.
If the model contains trainable Flax variables besides those defined by the
coroutine (for example, if `mean_fn` is a Flax module), the non-coroutine
variables are assumed to be unconstrained (the bijector passes them through
unmodified, and their lower/upp... | def get_constraints(
model: StochasticProcessModel, x: Optional[Any] = None
) -> Constraint:
"""Gets the parameter constraints from a StochasticProcessModel.
If the model contains trainable Flax variables besides those defined by the
coroutine (for example, if `mean_fn` is a Flax module), the non-coroutine
... |
Randomly initializes a coroutine's parameters. | def _initialize_params(
coroutine: ModelCoroutine, rng: jax.Array
) -> chex.ArrayTree:
"""Randomly initializes a coroutine's parameters."""
gen = coroutine()
params = {}
try:
p: ModelParameter = next(gen)
while True:
# Declare a Flax variable with the name and initialization function from
... |
A coroutine that follows the `ModelCoroutine` protocol. | def _test_coroutine(
inputs: Optional[types.ModelInput] = None,
num_tasks=1,
dtype=np.float64,
):
"""A coroutine that follows the `ModelCoroutine` protocol."""
kernel = yield from _kernel_coroutine(dtype=dtype)
if inputs is not None:
kernel = mask_features.MaskFeatures(
kernel,
dim... |
True if y2 > y1 (or y2 >= y1 if strict is False) every coordinate. | def _is_dominated(
y1: jt.Float[jt.Array, "M"],
y2: jt.Float[jt.Array, "M"],
strict: bool = True,
) -> jt.Bool[jt.Array, ""]:
"""True if y2 > y1 (or y2 >= y1 if strict is False) every coordinate."""
dominated_or_equal = jnp.all(y1 <= y2)
if strict:
return dominated_or_equal & jnp.any(y2 > y1)
el... |
Computes if nothing in `baseline` dominates `yy`.
Args:
yy: array of shape [B1, M] where M is number of metrics.
baseline: array of shape [B2, M] where M is number of metrics.
strict: If true, strict dominance is used.
Returns:
Boolean array of shape [B1] | def _is_pareto_optimal_against(
yy: jt.Float[jt.Array, "B1 M"],
baseline: jt.Float[jt.Array, "B2 M"],
*,
strict: bool,
) -> jt.Bool[jt.Array, "B1"]:
"""Computes if nothing in `baseline` dominates `yy`.
Args:
yy: array of shape [B1, M] where M is number of metrics.
baseline: array of shape [... |
Efficiently compute `_is_pareto_optimal_against(ys, ys, strict=True)`.
Divide `ys` into shards and gradually trim down the candidates.
Args:
ys: Array of shape [B, M] where M is number of metrics.
num_shards: Each sharding results in filtering, i.e. indexing the array with
boolean vector. This operation can b... | def is_frontier(
ys: jt.Float[jt.ArrayLike, "B M"],
*,
num_shards: int = 10,
verbose: bool = False,
) -> jt.Bool[jt.ArrayLike, "B"]:
"""Efficiently compute `_is_pareto_optimal_against(ys, ys, strict=True)`.
Divide `ys` into shards and gradually trim down the candidates.
Args:
ys: Array of sh... |
Efficiently compute `ys[_is_pareto_optimal_against(ys, ys, strict=True)]` using iterative filtering.
Divide `ys` into shards and gradually trim down the candidates.
`get_frontier` doesn't call `is_frontier`, because `get_frontier` runs faster
by not slicing the full `ys` every iteration.
Args:
ys: Array of shape [B... | def get_frontier(
ys: jt.Float[jt.ArrayLike, "B M"],
*,
num_shards: int = 10,
verbose: bool = True,
) -> jnp.ndarray:
"""Efficiently compute `ys[_is_pareto_optimal_against(ys, ys, strict=True)]` using iterative filtering.
Divide `ys` into shards and gradually trim down the candidates.
`get_fronti... |
Returns the pareto rank. | def pareto_rank(ys: jt.Float[jt.ArrayLike, "B M"]) -> jt.Int[jt.ArrayLike, "B"]:
"""Returns the pareto rank."""
jax_dominated_mv = jax.vmap(
functools.partial(_is_dominated, strict=True), (None, 0), 0
) # ([b,a], [a]) -> [b]
jax_dominated_mm = jax.vmap(
jax_dominated_mv, (0, None), 0
) # ([b,a... |
Returns a randomized approximation of the cumulative dominated hypervolume.
See Section 3, Lemma 5 of https://arxiv.org/pdf/2006.04655.pdf for a fuller
explanation of the technique. This assumes the reference point is the
origin.
NOTE: This returns an unnormalized hypervolume.
Args:
points: Any set of points with ... | def _cum_hypervolume_origin(
points: jt.Float[jt.ArrayLike, "B M"], vector: jt.Float[jt.Array, "... M"]
) -> jt.Float[jt.Array, "B"]:
"""Returns a randomized approximation of the cumulative dominated hypervolume.
See Section 3, Lemma 5 of https://arxiv.org/pdf/2006.04655.pdf for a fuller
explanation of the t... |
Take log-uniform sample in the constraint and map it back to \R.
Args:
low: Parameter lower bound.
high: Parameter upper bound.
shape: Returned array has this shape. Each entry in the returned array is an
i.i.d sample.
Returns:
Randomly sampled array. | def _log_uniform_init(
low: Union[float, np.floating],
high: Union[float, np.floating],
shape: tuple[int, ...] = tuple(),
) -> sp.InitFn:
r"""Take log-uniform sample in the constraint and map it back to \R.
Args:
low: Parameter lower bound.
high: Parameter upper bound.
shape: Returned array... |
Returns the top `best_n` parameters that minimize the losses.
Args:
losses: Shape (N,) array
all_params: ArrayTree whose leaves have shape (N, ...)
best_n: Integer greater than or equal to 1. If None, squeezes the leading
dimension.
Returns:
Top `best_n` parameters. | def get_best_params(
losses: jax.Array,
all_params: chex.ArrayTree,
*,
best_n: Optional[int] = None,
) -> chex.ArrayTree:
"""Returns the top `best_n` parameters that minimize the losses.
Args:
losses: Shape (N,) array
all_params: ArrayTree whose leaves have shape (N, ...)
best_n: Intege... |
Converts None bounds to inf or -inf to pass to the optimizer. | def _none_to_inf(b: float, inf: float, params: chex.ArrayTree):
"""Converts None bounds to inf or -inf to pass to the optimizer."""
if b is None:
b = inf
if _is_leaf(b):
# Broadcast scalars to the parameter structure.
return tree.map_structure(lambda x: b * jnp.ones_like(x), params)
else:
# For... |
Returns (Lower, upper) ArrayTrees with the same shape as params. | def _get_bounds(
params: core.Params,
constraints: Optional[sp.Constraint],
) -> Optional[tuple[chex.ArrayTree, chex.ArrayTree]]:
"""Returns (Lower, upper) ArrayTrees with the same shape as params."""
if constraints is None:
return None
else:
lb = _none_to_inf(constraints.bounds[0], -jnp.inf, para... |
Called by JaxoptLbfgsB. | def _run_parallel_lbfgs(
loss_fn: core.LossFunction[core.Params],
init_params_batch: core.Params,
*,
bounds: Optional[tuple[chex.ArrayTree, chex.ArrayTree]],
options: LbfgsBOptions,
) -> tuple[core.Params, Any]:
"""Called by JaxoptLbfgsB."""
def _run_one_lbfgs(
init_params: core.Params,
... |
Serialize (maybe) symbolic object to compressed JSON value. | def _to_json_str_compressed(value: Any) -> str:
"""Serialize (maybe) symbolic object to compressed JSON value."""
return base64.b64encode(
lzma.compress(json.dumps(
pg.to_json(value)).encode('utf-8'))).decode('ascii') |
Converts a parameter value to proper external type. | def _parameter_with_external_type(
val: vz.ParameterValueTypes,
external_type: vz.ExternalType) -> vz.ParameterValueTypes:
"""Converts a parameter value to proper external type."""
if external_type == vz.ExternalType.BOOLEAN:
# We output strings 'True' or 'False', not booleans themselves.
# because ... |
Make a decision point (DNASpec) out from a parameter config. | def _make_decision_point(
parameter_config: vz.ParameterConfig) -> pg.geno.DecisionPoint:
"""Make a decision point (DNASpec) out from a parameter config."""
# NOTE(daiyip): We set the name of each decision point instead of its
# location with parameter name.
#
# Why? For conditional space, the ID of a de... |
Converts a DNASpec to Vizier search space.
Args:
dna_spec:
Returns:
Vizier search space.
Raises:
NotImplementedError: If no part of the spec can be converted to a Vizier
parameter. | def _to_search_space(dna_spec: pg.DNASpec) -> vz.SearchSpace:
"""Converts a DNASpec to Vizier search space.
Args:
dna_spec:
Returns:
Vizier search space.
Raises:
NotImplementedError: If no part of the spec can be converted to a Vizier
parameter.
"""
def _parameter_name(path: pg.KeyPath... |
Returns scale type based on scale string. | def get_scale_type(scale: Optional[str]) -> Optional[vz.ScaleType]:
"""Returns scale type based on scale string."""
if scale in [None, 'linear']:
return vz.ScaleType.LINEAR
elif scale == 'log':
return vz.ScaleType.LOG
elif scale == 'rlog':
return vz.ScaleType.REVERSE_LOG
else:
raise ValueError... |
Extracts only the pyglove-related metadata into a simple dict. | def get_pyglove_metadata(trial: vz.Trial) -> dict[str, Any]:
"""Extracts only the pyglove-related metadata into a simple dict."""
metadata = dict()
# NOTE(daiyip): This is to keep backward compatibility for Cloud NAS service,
# which might loads trials from studies created in the old NAS pipeline for
# trans... |
Extracts only the pyglove-related metadata into a simple dict. | def get_pyglove_study_metadata(problem: vz.ProblemStatement) -> pg.Dict:
"""Extracts only the pyglove-related metadata into a simple dict."""
metadata = pg.Dict()
pg_metadata = problem.metadata.ns(constants.METADATA_NAMESPACE)
for key, value in pg_metadata.items():
if key not in constants.STUDY_METADATA_KE... |
Restores DNASpec from compressed JSON str. | def restore_dna_spec(json_str_compressed: str) -> pg.DNASpec:
"""Restores DNASpec from compressed JSON str."""
return pg.from_json(
json.loads(lzma.decompress(base64.b64decode(json_str_compressed)))
) |
From ':ns:key' to (ns, key). | def _parse_namespace_from_key(
encoded_key: str, default_ns: vz.Namespace
) -> tuple[vz.Namespace, str]:
"""From ':ns:key' to (ns, key)."""
ns_and_key = tuple(vz.Namespace.decode(encoded_key))
if not ns_and_key:
raise ValueError(
f'String did not parse into namespace and key: {encoded_key}'
)
... |
Init OSS Vizier backend.
Args:
study_prefix: An optional string that will be used as the prefix for the
study names created by `pg.sample` throughout the application. This allows
users to change the study names across multiple runs of the same binary
through this single venue, instead of modifying the `n... | def init(
study_prefix: Optional[str] = None,
vizier_endpoint: Optional[str] = None,
pythia_port: Optional[int] = None,
) -> None:
"""Init OSS Vizier backend.
Args:
study_prefix: An optional string that will be used as the prefix for the
study names created by `pg.sample` throughout the appli... |
Creates a Pythia policy that uses PyGlove algorithms. | def create_policy(
supporter: pythia.PolicySupporter,
problem_statement: vz.ProblemStatement,
algorithm: pg.geno.DNAGenerator,
early_stopping_policy: Optional[pg.tuning.EarlyStoppingPolicy] = None,
prior_trials: Optional[Sequence[vz.Trial]] = None,
) -> pythia.Policy:
"""Creates a Pythia policy th... |
Returns a randomized approximation of the cumulative dominated hypervolume.
See Section 3, Lemma 5 of https://arxiv.org/pdf/2006.04655.pdf for a fuller
explanation of the technique. This assumes the reference point is the
origin.
NOTE: This returns an unnormalized hypervolume.
Args:
points: Any set of points with ... | def _cum_hypervolume_origin(points: np.ndarray,
vectors: np.ndarray) -> np.ndarray:
"""Returns a randomized approximation of the cumulative dominated hypervolume.
See Section 3, Lemma 5 of https://arxiv.org/pdf/2006.04655.pdf for a fuller
explanation of the technique. This assumes the... |
Assigns value to $metadatum. | def _assign_value(
metadatum: key_value_pb2.KeyValue, value: Union[str, any_pb2.Any, Message]
) -> None:
"""Assigns value to $metadatum."""
if isinstance(value, str):
metadatum.ClearField('proto')
metadatum.value = value
elif isinstance(value, any_pb2.Any):
metadatum.ClearField('value')
metad... |
Insert and/or assign (key, value) to container.metadata.
Args:
container: container.metadata must be repeated KeyValue (protobuf) field.
key:
ns: A namespace for the key (defaults to '', which is the user's namespace).
value: Behavior depends on the type. `str` is copied to KeyValue.value
`any_pb2.Any` is ... | def assign(
container: Union[study_pb2.StudySpec, study_pb2.Trial],
*,
key: str,
ns: str,
value: Union[str, any_pb2.Any, Message],
mode: Literal['insert_or_assign', 'insert_or_error', 'insert'] = 'insert',
) -> Tuple[key_value_pb2.KeyValue, bool]:
"""Insert and/or assign (key, value) to contai... |
Returns the metadata value associated with key, or None.
Args:
container: A Trial of a StudySpec in protobuf form.
key: The key of a KeyValue protobuf.
ns: A namespace for the key (defaults to '', which is the user's namespace). | def get(
container: Union[study_pb2.StudySpec, study_pb2.Trial], *, key: str, ns: str
) -> Optional[str]:
"""Returns the metadata value associated with key, or None.
Args:
container: A Trial of a StudySpec in protobuf form.
key: The key of a KeyValue protobuf.
ns: A namespace for the key (defaults ... |
Unpacks the proto metadata into message.
Args:
container: (const) StudySpec or Trial to search the metadata from.
key: (const) Lookup key of the metadata.
ns: A namespace for the key (defaults to '', which is the user's namespace).
cls: Pass in a proto ***class***, not a proto object.
Returns:
Proto message... | def get_proto(
container: Union[study_pb2.StudySpec, study_pb2.Trial],
*,
key: str,
ns: str,
cls: Type[T],
) -> Optional[T]:
"""Unpacks the proto metadata into message.
Args:
container: (const) StudySpec or Trial to search the metadata from.
key: (const) Lookup key of the metadata.
... |
Convert $metadata to a list of KeyValue protobufs. | def make_key_value_list(
metadata: common.Metadata,
) -> list[key_value_pb2.KeyValue]:
"""Convert $metadata to a list of KeyValue protobufs."""
result = []
for ns, k, v in metadata.all_items():
item = key_value_pb2.KeyValue(key=k, ns=ns.encode())
_assign_value(item, v)
result.append(item)
return... |
Converts a list of KeyValue protos into a Metadata object. | def from_key_value_list(
kv_s: Iterable[key_value_pb2.KeyValue],
) -> common.Metadata:
"""Converts a list of KeyValue protos into a Metadata object."""
metadata = common.Metadata()
for kv in kv_s:
metadata.abs_ns(common.Namespace.decode(kv.ns))[kv.key] = (
kv.proto if kv.HasField('proto') else kv.... |
Convert a dictionary of Trial.id:Metadata to a list of UnitMetadataUpdate.
Args:
trial_metadata: Typically MetadataDelta.on_trials.
Returns:
a list of UnitMetadataUpdate objects. | def trial_metadata_to_update_list(
trial_metadata: dict[int, common.Metadata]
) -> list[vizier_service_pb2.UnitMetadataUpdate]:
"""Convert a dictionary of Trial.id:Metadata to a list of UnitMetadataUpdate.
Args:
trial_metadata: Typically MetadataDelta.on_trials.
Returns:
a list of UnitMetadataUpdate... |
Convert `on_study` metadata to list of metadata update protos. | def study_metadata_to_update_list(
study_metadata: common.Metadata,
) -> list[vizier_service_pb2.UnitMetadataUpdate]:
"""Convert `on_study` metadata to list of metadata update protos."""
unit_metadata_updates = []
for ns, k, v in study_metadata.all_items():
unit_metadata_update = vizier_service_pb2.UnitMe... |
Create an UpdateMetadataRequest proto.
Args:
study_resource_name:
delta:
Returns: | def to_request_proto(
study_resource_name: str, delta: trial.MetadataDelta
) -> vizier_service_pb2.UpdateMetadataRequest:
"""Create an UpdateMetadataRequest proto.
Args:
study_resource_name:
delta:
Returns:
"""
request = vizier_service_pb2.UpdateMetadataRequest(name=study_resource_name)
# Stu... |
Merges $new_metadata into a Study's existing metadata. | def merge_study_metadata(
study_spec: study_pb2.StudySpec,
new_metadata: Iterable[key_value_pb2.KeyValue],
) -> None:
"""Merges $new_metadata into a Study's existing metadata."""
metadata_dict: Dict[Tuple[str, str], key_value_pb2.KeyValue] = {}
for kv in study_spec.metadata:
metadata_dict[(kv.ns, kv.k... |
Merges $new_metadata into a Trial's existing metadata.
Args:
trial_proto: A representation of a Trial; this will be modified.
new_metadata: Metadata that will add or update metadata in the Trial.
NOTE: the metadata updates in $new_metadata should have the same ID as
$trial_proto. | def merge_trial_metadata(
trial_proto: study_pb2.Trial,
new_metadata: Iterable[vizier_service_pb2.UnitMetadataUpdate],
) -> None:
"""Merges $new_metadata into a Trial's existing metadata.
Args:
trial_proto: A representation of a Trial; this will be modified.
new_metadata: Metadata that will add or ... |
from_proto conversion for Trial statuses. | def _to_pyvizier_trial_status(
proto_state: study_pb2.Trial.State,
) -> trial.TrialStatus:
"""from_proto conversion for Trial statuses."""
if proto_state == study_pb2.Trial.State.REQUESTED:
return trial.TrialStatus.REQUESTED
elif proto_state == study_pb2.Trial.State.ACTIVE:
return trial.TrialStatus.AC... |
to_proto conversion for Trial states. | def _from_pyvizier_trial_status(
status: trial.TrialStatus, infeasible: bool
) -> study_pb2.Trial.State:
"""to_proto conversion for Trial states."""
if status == trial.TrialStatus.REQUESTED:
return study_pb2.Trial.State.REQUESTED
elif status == trial.TrialStatus.ACTIVE:
return study_pb2.Trial.State.AC... |
Parses an encoded namespace string into a namespace tuple. | def _parse(arg: str) -> Tuple[str, ...]:
"""Parses an encoded namespace string into a namespace tuple."""
# The tricky part here is that arg.split('') has a length of 1, so it can't
# generate a zero-length tuple; we handle that corner case manually.
if not arg:
return ()
# And, then, once we've handled t... |
Validates the bounds. | def _validate_bounds(bounds: Union[Tuple[int, int], Tuple[float, float]]):
"""Validates the bounds."""
if len(bounds) != 2:
raise ValueError(f'Bounds must have length 2. Given: {bounds}')
lower = bounds[0]
upper = bounds[1]
if not all([math.isfinite(v) for v in (lower, upper)]):
raise ValueError(
... |
Validates and converts feasible values to floats. | def _get_feasible_points_and_bounds(
feasible_values: Sequence[float],
) -> Tuple[List[float], Union[Tuple[int, int], Tuple[float, float]]]:
"""Validates and converts feasible values to floats."""
if not all([math.isfinite(p) for p in feasible_values]):
raise ValueError(
f'Feasible values must all b... |
Returns the categories. | def _get_categories(categories: Sequence[str]) -> List[str]:
"""Returns the categories."""
return sorted(list(categories)) |
Validates and converts the default_value to the right type. | def _get_default_value(
param_type: ParameterType, default_value: Union[float, int, str]
) -> Union[float, int, str]:
"""Validates and converts the default_value to the right type."""
if param_type in (ParameterType.DOUBLE, ParameterType.DISCRETE) and (
isinstance(default_value, float) or isinstance(defau... |
Converter for initializing timestamps in Trial class. | def _to_local_time(
dt: Optional[datetime.datetime]) -> Optional[datetime.datetime]:
"""Converter for initializing timestamps in Trial class."""
return dt.astimezone() if dt else None |
Distributes tuning via Ray datasets API for MapReduce purposes.
NOTE: There are no datasets processed. However, all MapReduce operations
are now done in the Datasets API under Ray.
Args:
run_tune_args_list: List of Tuples that are to be passed into run_tune.
run_tune: Callable that accepts args from previous list... | def run_tune_distributed(
run_tune_args_list: List[Tuple[Any]],
run_tune: Callable[[Any], tune.result_grid.ResultGrid],
) -> List[tune.result_grid.ResultGrid]:
"""Distributes tuning via Ray datasets API for MapReduce purposes.
NOTE: There are no datasets processed. However, all MapReduce operations
are n... |
Runs Ray Tuners for BBOB problems.
See https://docs.ray.io/en/latest/tune/key-concepts.html
For more information on Tune and Run configs, see
https://docs.ray.io/en/latest/ray-air/tuner.html
Args:
function_name: BBOB function name.
dimension: Dimension of BBOB function.
shift: Shift of BBOB function.
tune_con... | def run_tune_bbob(
function_name: str,
dimension: int,
shift: Optional[np.ndarray] = None,
tune_config: Optional[tune.TuneConfig] = None,
run_config: Optional[air.RunConfig] = None,
) -> tune.result_grid.ResultGrid:
"""Runs Ray Tuners for BBOB problems.
See https://docs.ray.io/en/latest/tune/ke... |
Runs Ray Tuners from an Experimenter Factory.
See https://docs.ray.io/en/latest/tune/key-concepts.html
For more information on Tune and Run configs, see
https://docs.ray.io/en/latest/ray-air/tuner.html
Args:
experimenter_factory: Experimenter Factory.
tune_config: Ray Tune Config.
run_config: Ray Run Config.
R... | def run_tune_from_factory(
experimenter_factory: experimenters.ExperimenterFactory,
tune_config: Optional[tune.TuneConfig] = None,
run_config: Optional[air.RunConfig] = None,
) -> tune.result_grid.ResultGrid:
"""Runs Ray Tuners from an Experimenter Factory.
See https://docs.ray.io/en/latest/tune/key-co... |
Converts custom exception into correct context error code.
The rules for gRPC are:
1) In the remote case (servicer wrapped into a server), the context is
automatically generated by gRPC. Calling `context.set_code()` will
automatically trigger an ` _InactiveRpcError` on the client side, which can
collect the code and ... | def handle_exception(
e: Exception, context: Optional[grpc.ServicerContext] = None
) -> None:
"""Converts custom exception into correct context error code.
The rules for gRPC are:
1) In the remote case (servicer wrapped into a server), the context is
automatically generated by gRPC. Calling `context.set_c... |
Creates GRPC channel. | def _create_channel(
endpoint: str, timeout: Optional[float] = None
) -> grpc.Channel:
"""Creates GRPC channel."""
logging.info('Securing channel to %s.', endpoint)
channel = grpc.insecure_channel(endpoint)
grpc.channel_ready_future(channel).result(timeout=timeout)
logging.info('Created channel to %s.', e... |
Creates the GRPC stub.
This method uses LRU cache so we create a single stub per endpoint (which is
effectively one per binary). Stub and channel are both thread-safe and can
take a while to create. The LRU cache makes binaries run faster, especially
for unit tests.
Args:
endpoint: Pythia server endpoint.
timeout... | def create_pythia_server_stub(
endpoint: str, timeout: Optional[float] = 10.0
) -> pythia_service_pb2_grpc.PythiaServiceStub:
"""Creates the GRPC stub.
This method uses LRU cache so we create a single stub per endpoint (which is
effectively one per binary). Stub and channel are both thread-safe and can
tak... |
Creates the GRPC stub.
This method uses LRU cache so we create a single stub per endpoint (which is
effectively one per binary). Stub and channel are both thread-safe and can
take a while to create. The LRU cache makes binaries run faster, especially
for unit tests.
Args:
endpoint: Vizier server endpoint.
timeout... | def create_vizier_server_stub(
endpoint: str, timeout: Optional[float] = 10.0
) -> vizier_service_pb2_grpc.VizierServiceStub:
"""Creates the GRPC stub.
This method uses LRU cache so we create a single stub per endpoint (which is
effectively one per binary). Stub and channel are both thread-safe and can
tak... |
Factory method for creating or loading a VizierClient.
This will either create or load the specified study, given
(owner_id, study_id, study_config). It will create it if it doesn't
already exist, and load it if someone has already created it.
Note that once a study is created, you CANNOT modify it with this function... | def create_or_load_study(
owner_id: str,
client_id: str,
study_id: str,
study_config: pyvizier.StudyConfig,
) -> VizierClient:
"""Factory method for creating or loading a VizierClient.
This will either create or load the specified study, given
(owner_id, study_id, study_config). It will create it... |
Computes a delay to the next attempt to poll the Vizier service.
This does bounded exponential backoff, starting with $time_scale.
If $time_scale == 0, it starts with a small time interval, less than
1 second.
Args:
num_attempts: The number of times have we polled and found that the desired
result was not yet a... | def PollingDelay(num_attempts: int, time_scale: float) -> datetime.timedelta: # pylint:disable=invalid-name
"""Computes a delay to the next attempt to poll the Vizier service.
This does bounded exponential backoff, starting with $time_scale.
If $time_scale == 0, it starts with a small time interval, less than
... |
Generates arbitrary trials. | def generate_trials(trial_id_list: Sequence[int],
owner_id: str = 'my_username',
study_id: str = '1234',
**trial_kwargs) -> List[study_pb2.Trial]:
"""Generates arbitrary trials."""
trials = []
for trial_id in trial_id_list:
trial = study_pb2.Trial(
... |
Generates a trial for each possible trial state. | def generate_all_states_trials(start_trial_index: int,
owner_id: str = 'my_username',
study_id: str = '1234',
**trial_kwargs) -> List[study_pb2.Trial]:
"""Generates a trial for each possible trial state."""
trials = []
fo... |
Generates arbitrary suggestion operations. | def generate_suggestion_operations(
operation_numbers: Sequence[int],
owner_id: str = 'my_username',
study_id: str = 'cifar10',
client_id: str = 'client0',
**operation_kwargs) -> List[operations_pb2.Operation]:
"""Generates arbitrary suggestion operations."""
operations = []
for operation_numb... |
Generates arbitrary early stopping operations. | def generate_early_stopping_operations(
trial_id_list: Sequence[int],
owner_id: str = 'my_username',
study_id: str = '1234',
**operation_kwargs) -> List[vizier_oss_pb2.EarlyStoppingOperation]:
"""Generates arbitrary early stopping operations."""
operations = []
for trial_id in trial_id_list:
o... |
All possible primitive parameter specs for testing. | def generate_all_four_parameter_specs(**study_spec_kwargs
) -> study_pb2.StudySpec:
"""All possible primitive parameter specs for testing."""
double_value_spec = study_pb2.StudySpec.ParameterSpec.DoubleValueSpec(
min_value=-1.0, max_value=1.0)
double_parameter_spec = stu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.