google-research
70 строк · 2.4 Кб
1# coding=utf-8
2# Copyright 2024 The Google Research Authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""Generating random search spaces given a base search space."""
17import jax18import jax.numpy as jnp19
20# pylint: disable=g-doc-return-or-yield
21# pylint: disable=line-too-long
22
23
24def random_subinterval(key, interval, reduce_rate):25"""Generate a reduced interval from a base interval.26
27Args:
28key: PRNG key for jax.random.
29interval: (2,) shaped array of min and max values of the interval.
30reduce_rate: interval reduction rate in (0, 1].
31
32Returns: (2,) shaped array of min and max values of the new interval.
33"""
34lower = interval[0]35upper = interval[1]36target_length = reduce_rate * (upper - lower)37lower_new = jax.random.uniform(38key, minval=lower, maxval=upper - target_length)39upper_new = lower_new + target_length40return jnp.array([lower_new, upper_new])41
42
43def generate_search_space_reduce_vol(key, search_space, reduce_rate=1/2):44"""Generate a reduced volumed search space from a base search space.45
46Args:
47key: PRNG key for jax.random.
48search_space: (d,2) shaped array of min and max values.
49reduce_rate: volume reduction rate in (0, 1].
50
51Returns: (d,2) shaped array of min and max values of the new search space.
52"""
53reduce_rate_dim = reduce_rate**(1/search_space.shape[0])54keys = jax.random.split(key, search_space.shape[0])55search_space_reduced = jax.vmap(56random_subinterval, in_axes=(0, 0, None))(keys, search_space,57reduce_rate_dim)58condition = reduce_rate == 159return jnp.where(condition, search_space, search_space_reduced)60
61
62def eval_vol(search_space):63"""Compute volume of a hyperrectangular search space.64
65Args:
66search_space: (d,2) shaped array of min and max values.
67
68Returns: volume of the search space.
69"""
70return jnp.prod(search_space[:, 1]-search_space[:, 0])71