index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
47,048 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyglove/oss_vizier_test.py | 32,34 | 30,55 | setUpClass | OSSVizierSampleTest | 34,46 | 34,46 | class OSSVizierSampleTest(vizier_test_lib.SampleTest):
@classmethod
def setUpClass(cls):
FILL_FUNC_BODY def __init__(self, *args, **kwargs):
super().__init__(
vizier.OSSVizierBackend,
*args,
builtin_multiobjective_algorithm_to_test='NSGA2',
**kwargs,
)
| class OSSVizierSampleTest(vizier_test_lib.SampleTest):
@classmethod
def setUpClass(cls):
FILL_FUNC_BODY def __init__(self, *args, **kwargs):
super().__init__(
vizier.OSSVizierBackend,
*args,
builtin_multiobjective_algorithm_to_test='NSGA2',
**kwargs,
)
| super().setUpClass()
server = vizier_server.DefaultVizierServer(
host=os.uname()[1],
database_url=constants.SQL_MEMORY_URL,
early_stop_recycle_period=datetime.timedelta(seconds=0.0),
)
logging.info(server.endpoint)
vizier._services.reset_for_testing()
vizier.init(vizier_e... | super().setUpClass()
server = vizier_server.DefaultVizierServer(
host=os.uname()[1],
database_url=constants.SQL_MEMORY_URL,
early_stop_recycle_period=datetime.timedelta(seconds=0.0),
)
logging.info(server.endpoint)
vizier._services.reset_for_testing()
vizier.init(vizier_e... | 20 | 116 | 160 | 276 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,051 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pythia/policy.py | 130,132 | 99,139 | study_config | EarlyStopRequest | 132,134 | 132,134 | @attr.define
class EarlyStopRequest:
"""Early stopping request.
Attributes:
study_guid:
trial_ids: Trials to be considered for stopping, or None meaning "all
Trials". This is a hint; it is allowable to consider stopping more or
fewer trials.
study_config:
checkpoint_dir: If the policy w... | @attr.define
class EarlyStopRequest:
"""Early stopping request.
Attributes:
study_guid:
trial_ids: Trials to be considered for stopping, or None meaning "all
Trials". This is a hint; it is allowable to consider stopping more or
fewer trials.
study_config:
checkpoint_dir: If the policy w... | return self._study_descriptor.config
| return self._study_descriptor.config
| 2 | 411 | 15 | 426 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,052 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pythia/policy.py | 259,261 | 207,275 | name | Policy | 262,265 | 261,265 | class Policy(abc.ABC):
"""Interface for Pythia Policy subclasses.
Most Policy subclasses would wish to take `PolicySupporter` object in the
`__init__` function. `PolicySupporter` provides an abstraction for how
`Policy` reads more information about the Study in question beyond the basic
information available... | class Policy(abc.ABC):
"""Interface for Pythia Policy subclasses.
Most Policy subclasses would wish to take `PolicySupporter` object in the
`__init__` function. `PolicySupporter` provides an abstraction for how
`Policy` reads more information about the Study in question beyond the basic
information available... | # Derived classes should override this implementation.
return __class__.__name__
| """Returns the policy name. Intended for monitoring purposes only."""
# Derived classes should override this implementation.
return __class__.__name__
| 9 | 711 | 24 | 735 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,053 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pythia/policy.py | 194,196 | 164,207 | study_config | SuggestRequest | 196,198 | 196,198 | @attr.define
class SuggestRequest:
"""Suggestion Request.
Attributes:
study_descriptor: information about the Study.
study_guid: Study id
count: A recommendation for how many suggestions should be generated.
study_config:
checkpoint_dir: (If set) A system-provided directory where the policy can... | @attr.define
class SuggestRequest:
"""Suggestion Request.
Attributes:
study_descriptor: information about the Study.
study_guid: Study id
count: A recommendation for how many suggestions should be generated.
study_config:
checkpoint_dir: (If set) A system-provided directory where the policy can... | return self._study_descriptor.config
| return self._study_descriptor.config
| 2 | 425 | 15 | 440 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,054 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pythia/policy_supporter.py | 121,122 | 26,134 | TimeRemaining | PolicySupporter | 133,134 | 122,134 | class PolicySupporter(abc.ABC):
"""Used by Policy instances to communicate with Vizier."""
# TODO: Change to GetStudyDescriptor (Maybe: Note that
# StudyDescriptor includes $max_trial_id, so it causes many more database
# collisions than ProblemStatement, especially if there are lots of
# workers.)
@... | class PolicySupporter(abc.ABC):
"""Used by Policy instances to communicate with Vizier."""
# TODO: Change to GetStudyDescriptor (Maybe: Note that
# StudyDescriptor includes $max_trial_id, so it causes many more database
# collisions than ProblemStatement, especially if there are lots of
# workers.)
@... | return datetime.timedelta(hours=1.0)
| """The time remaining to compute a result.
Returns:
The remaining time before the RPC is considered to have timed out; it
returns datetime.timedelta.max if no deadline was specified in the RPC.
This is an alternative to calling CheckCancelled(); both have the goal of
terminating runaway co... | 2 | 1,180 | 16 | 1,196 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,055 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pythia/suggest_default.py | 57,58 | 1,112 | seed_with_default | 86,112 | 58,112 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
if hasattr(suggest_fn, '__self__'):
unbound = seed_with_default(suggest_fn.__func__)
return types.MethodType(unbound, suggest_fn.__self__)
@functools.wraps(suggest_fn)
def wrapper_fn(self: Policy, request: SuggestRequest) -> SuggestDecision:
"""If study is empty, suggests a default trial before usin... | """Decorator for Policy.suggest to always suggest the default or center.
How to use as a decorator:
```
class MyPolicy(Policy):
@seed_with_default
def suggest(self, ...):
...
```
How to use as a function:
class MyPolicy(Policy):
def __init__(self, ..., *, use_seed_with_default: bool)... | 65 | 773 | 296 | 1,069 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
47,056 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pythia/suggest_default_test.py | 78,82 | 76,95 | suggest | FakeDecoratedPolicy | 82,90 | 82,90 | class FakeDecoratedPolicy(pythia.Policy):
@suggest_default.seed_with_default
def suggest(
self, request: pythia.SuggestRequest
) -> pythia.SuggestDecision:
FILL_FUNC_BODY def early_stop(
self, request: pythia.EarlyStopRequest
) -> pythia.EarlyStopDecisions:
... | class FakeDecoratedPolicy(pythia.Policy):
@suggest_default.seed_with_default
def suggest(
self, request: pythia.SuggestRequest
) -> pythia.SuggestDecision:
FILL_FUNC_BODY def early_stop(
self, request: pythia.EarlyStopRequest
) -> pythia.EarlyStopDecisions:
... | if request.count != 2:
raise ValueError(f'count must be 2. Was: {request.count}')
if request._study_descriptor != empty_study_descriptor:
raise ValueError('study_descriptor must match request')
return pythia.SuggestDecision(
[vz.TrialSuggestion({'x': 999}), vz.Tri... | if request.count != 2:
raise ValueError(f'count must be 2. Was: {request.count}')
if request._study_descriptor != empty_study_descriptor:
raise ValueError('study_descriptor must match request')
return pythia.SuggestDecision(
[vz.TrialSuggestion({'x': 999}), vz.Tri... | 27 | 121 | 130 | 251 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,057 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pythia/suggest_default_test.py | 105,108 | 100,121 | suggest | FakeInitOverridePolicy | 108,116 | 108,116 | class FakeInitOverridePolicy(pythia.Policy):
def __init__(self):
self.suggest = suggest_default.seed_with_default(self.suggest)
def suggest(
self, request: pythia.SuggestRequest
) -> pythia.SuggestDecision:
FILL_FUNC_BODY def early_stop(
self, request: pythia.Ear... | class FakeInitOverridePolicy(pythia.Policy):
def __init__(self):
self.suggest = suggest_default.seed_with_default(self.suggest)
def suggest(
self, request: pythia.SuggestRequest
) -> pythia.SuggestDecision:
FILL_FUNC_BODY def early_stop(
self, request: pythia.Ear... | if request.count != 2:
raise ValueError(f'count must be 2. Was: {request.count}')
if request._study_descriptor != empty_study_descriptor:
raise ValueError('study_descriptor must match request')
return pythia.SuggestDecision(
[vz.TrialSuggestion({'x': 999}), vz.Tri... | if request.count != 2:
raise ValueError(f'count must be 2. Was: {request.count}')
if request._study_descriptor != empty_study_descriptor:
raise ValueError('study_descriptor must match request')
return pythia.SuggestDecision(
[vz.TrialSuggestion({'x': 999}), vz.Tri... | 27 | 137 | 130 | 267 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,058 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pythia/suggest_default_test.py | 66,67 | 37,73 | test_categorical | GetDefaultParametersTest | 67,73 | 67,73 | class GetDefaultParametersTest(absltest.TestCase):
def test_double_user_default(self):
ss = vz.SearchSpace()
ss.root.add_float_param('x', 0.0, 1.0, default_value=0.2)
params = suggest_default._get_default_parameters(ss)
self.assertEqual(params.get_value('x'), 0.2)
@unittest.skip('TODO')
def test... | class GetDefaultParametersTest(absltest.TestCase):
def test_double_user_default(self):
ss = vz.SearchSpace()
ss.root.add_float_param('x', 0.0, 1.0, default_value=0.2)
params = suggest_default._get_default_parameters(ss)
self.assertEqual(params.get_value('x'), 0.2)
@unittest.skip('TODO')
def test... | ss = vz.SearchSpace()
ss.root.add_categorical_param('x', ['a', 'b', 'c', 'd'])
params = suggest_default._get_default_parameters(ss)
self.assertEqual(params.get_value('x'), 'c')
| ss = vz.SearchSpace()
ss.root.add_categorical_param('x', ['a', 'b', 'c', 'd'])
params = suggest_default._get_default_parameters(ss)
self.assertEqual(params.get_value('x'), 'c')
| 13 | 401 | 79 | 480 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,059 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pythia/suggest_default_test.py | 99,100 | 73,126 | test_init_override | SuggestDefaultTest | 100,126 | 100,126 | class SuggestDefaultTest(absltest.TestCase):
def test_decorator(self):
class FakeDecoratedPolicy(pythia.Policy):
@suggest_default.seed_with_default
def suggest(
self, request: pythia.SuggestRequest
) -> pythia.SuggestDecision:
if request.count != 2:
raise ValueError... | class SuggestDefaultTest(absltest.TestCase):
def test_decorator(self):
class FakeDecoratedPolicy(pythia.Policy):
@suggest_default.seed_with_default
def suggest(
self, request: pythia.SuggestRequest
) -> pythia.SuggestDecision:
if request.count != 2:
raise ValueError... | class FakeInitOverridePolicy(pythia.Policy):
def __init__(self):
self.suggest = suggest_default.seed_with_default(self.suggest)
def suggest(
self, request: pythia.SuggestRequest
) -> pythia.SuggestDecision:
if request.count != 2:
raise ValueError(f'count must ... | class FakeInitOverridePolicy(pythia.Policy):
def __init__(self):
self.suggest = suggest_default.seed_with_default(self.suggest)
def suggest(
self, request: pythia.SuggestRequest
) -> pythia.SuggestDecision:
if request.count != 2:
raise ValueError(f'count must ... | 56 | 321 | 317 | 638 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,060 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/multimetric/hypervolume.py | 25,27 | 1,168 | _cum_hypervolume_origin | 45,68 | 27,68 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | if vectors.shape[1] != points.shape[1]:
raise ValueError(f'Vectors shape {vectors.shape} do not match dimension of'
f' (second value in tuple of points shape {points.shape}')
num_points, dimension = points.shape
num_vectors = vectors.shape[0]
temp_points = np.broadcast_to(points[np.newa... | """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 se... | 120 | 1,672 | 371 | 2,043 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
47,061 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/multimetric/hypervolume.py | 109,113 | 68,168 | hypervolume | ParetoFrontier | 132,168 | 113,168 | class ParetoFrontier:
"""Calculate hypervolume approximations for a Pareto frontier/set."""
def __init__(
self,
points: np.ndarray,
origin: np.ndarray,
num_vectors: int = 10000,
cum_hypervolume_base: Callable[[np.ndarray, np.ndarray],
np.ndarray] =... | class ParetoFrontier:
"""Calculate hypervolume approximations for a Pareto frontier/set."""
def __init__(
self,
points: np.ndarray,
origin: np.ndarray,
num_vectors: int = 10000,
cum_hypervolume_base: Callable[[np.ndarray, np.ndarray],
np.ndarray] =... | if additional_points is None:
points = self._points
else:
if self._points.shape[1] != additional_points.shape[1]:
raise ValueError(
f'Dimension mismatch frontier points {self._points.shape}'
f' and additional points {additional_points.shape}')
points = np.concat... | """Returns a randomized approximation of the dominated hypervolume.
See Section 3, Lemma 5 of https://arxiv.org/pdf/2006.04655.pdf for a fuller
explanation of the technique.
Args:
additional_points: Additional 2D array to add to hypervolume computation.
is_cumulative: If true, a cumulative... | 162 | 779 | 526 | 1,305 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,062 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/multimetric/hypervolume_test.py | 36,37 | 23,65 | testParetoHypervolumeCumulative | HypervolumeTest | 37,49 | 37,49 | class HypervolumeTest(absltest.TestCase):
def testParetoHypervolume(self):
x = np.random.normal()
y = np.random.normal()
points = np.array([[x, y], [y, x]])
origin = np.array([-1, -1])
pf = hypervolume.ParetoFrontier(points, origin)
self.assertAlmostEqual(
pf.hypervolume(),
ma... | class HypervolumeTest(absltest.TestCase):
def testParetoHypervolume(self):
x = np.random.normal()
y = np.random.normal()
points = np.array([[x, y], [y, x]])
origin = np.array([-1, -1])
pf = hypervolume.ParetoFrontier(points, origin)
self.assertAlmostEqual(
pf.hypervolume(),
ma... | points = np.random.normal(size=(100, 4))
origin = np.zeros(4)
pf = hypervolume.ParetoFrontier(points, origin)
cumulative_vol = pf.hypervolume(is_cumulative=True)
self.assertLen(cumulative_vol, len(points))
for i in range(len(points)):
if i < len(points) - 1:
self.assertGreaterEqua... | points = np.random.normal(size=(100, 4))
origin = np.zeros(4)
pf = hypervolume.ParetoFrontier(points, origin)
cumulative_vol = pf.hypervolume(is_cumulative=True)
self.assertLen(cumulative_vol, len(points))
for i in range(len(points)):
if i < len(points) - 1:
self.assertGreaterEqua... | 33 | 442 | 180 | 622 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,063 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/multimetric/pareto_optimal.py | 66,69 | 24,87 | update_pareto_optimal | BaseParetoOptimalAlgorithm | 81,87 | 69,87 | class BaseParetoOptimalAlgorithm(metaclass=abc.ABCMeta):
"""Base metaclass for calculating pareto frontiers."""
@abc.abstractmethod
def is_pareto_optimal(self, points: np.ndarray) -> np.ndarray:
"""An algorithm to find the Pareto frontier.
Args:
points: M-by-D 2D array of points. M = number of poi... | class BaseParetoOptimalAlgorithm(metaclass=abc.ABCMeta):
"""Base metaclass for calculating pareto frontiers."""
@abc.abstractmethod
def is_pareto_optimal(self, points: np.ndarray) -> np.ndarray:
"""An algorithm to find the Pareto frontier.
Args:
points: M-by-D 2D array of points. M = number of poi... | is_optimal = self.is_pareto_optimal(
np.append(current_pareto_optimal, incremental_points, axis=0)
)
return np.asarray(is_optimal).nonzero()[0]
| """An algorithm to update the Pareto frontier.
Args:
current_pareto_optimal: M-by-D 2D array of current pareto optimal points.
M = number of points, D = dimension.
incremental_points: N-by-D 2D array of incremental points. N = number of
points, D = dimension.
Returns:
Lis... | 9 | 638 | 66 | 704 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,064 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/multimetric/pareto_optimal.py | 235,236 | 121,261 | is_pareto_optimal | FastParetoOptimalAlgorithm | 237,261 | 236,261 | class FastParetoOptimalAlgorithm(BaseParetoOptimalAlgorithm):
"""Fast DC/recursive algorithm deciding if points are optimal or dominated.
NOTE: p dominates q if p_i >= q_i and strictly if p_i != q_i.
Citation on first publication:
https://static.aminer.org/pdf/PDF/000/211/201/on_the_computational_complexity_o... | class FastParetoOptimalAlgorithm(BaseParetoOptimalAlgorithm):
"""Fast DC/recursive algorithm deciding if points are optimal or dominated.
NOTE: p dominates q if p_i >= q_i and strictly if p_i != q_i.
Citation on first publication:
https://static.aminer.org/pdf/PDF/000/211/201/on_the_computational_complexity_o... |
# Base case naive algorithm for find Pareto optimality.
if len(points) <= self._recursive_threshold:
return np.array(
self._base_algorithm.is_pareto_optimal(points), dtype=bool)
# Sort from lowest to highest on first dimension and split.
ascending_indices = (points[:, 0]).argsort()
... | """Fast DC algorithm to find the Pareto frontier. See base class."""
# Base case naive algorithm for find Pareto optimality.
if len(points) <= self._recursive_threshold:
return np.array(
self._base_algorithm.is_pareto_optimal(points), dtype=bool)
# Sort from lowest to highest on first ... | 85 | 1,379 | 354 | 1,733 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,065 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/multimetric/pareto_optimal.py | 109,110 | 87,121 | is_pareto_optimal | NaiveParetoOptimalAlgorithm | 111,121 | 110,121 | class NaiveParetoOptimalAlgorithm(BaseParetoOptimalAlgorithm):
"""Naive implementation of Pareto frontier calculation."""
def is_pareto_optimal_against(self, points: np.ndarray, against: np.ndarray,
*, strict: bool) -> np.ndarray:
"""Naive quadratic-time implementation. See base... | class NaiveParetoOptimalAlgorithm(BaseParetoOptimalAlgorithm):
"""Naive implementation of Pareto frontier calculation."""
def is_pareto_optimal_against(self, points: np.ndarray, against: np.ndarray,
*, strict: bool) -> np.ndarray:
"""Naive quadratic-time implementation. See base... | is_optimal = np.ones(len(points), dtype=bool)
for i, point in enumerate(points):
if is_optimal[i]:
# At each step, revise all potentially optimal points.
is_optimal[is_optimal] = (
np.any(points[is_optimal] > point, axis=1)
| np.all(points[is_optimal] == point, axis... | """Naive quadratic-time implementation. See base class."""
is_optimal = np.ones(len(points), dtype=bool)
for i, point in enumerate(points):
if is_optimal[i]:
# At each step, revise all potentially optimal points.
is_optimal[is_optimal] = (
np.any(points[is_optimal] > point,... | 34 | 339 | 123 | 462 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,066 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/multimetric/pareto_optimal_test.py | 42,43 | 25,102 | test_is_pareto_optimal_all_optimal | ParetoOptimalTest | 43,51 | 43,51 | class ParetoOptimalTest(absltest.TestCase):
def setUp(self):
super(ParetoOptimalTest, self).setUp()
self.algo = pareto_optimal.FastParetoOptimalAlgorithm(
base_algorithm=pareto_optimal.NaiveParetoOptimalAlgorithm())
def test_is_pareto_optimal(self):
points = np.array([[1, 2, 3], [1, 2, 3], [2,... | class ParetoOptimalTest(absltest.TestCase):
def setUp(self):
super(ParetoOptimalTest, self).setUp()
self.algo = pareto_optimal.FastParetoOptimalAlgorithm(
base_algorithm=pareto_optimal.NaiveParetoOptimalAlgorithm())
def test_is_pareto_optimal(self):
points = np.array([[1, 2, 3], [1, 2, 3], [2,... | # Generate points on positive orthant sphere.
points = abs(np.random.normal(size=(1000, 3)))
points /= np.linalg.norm(points, axis=1)[..., np.newaxis]
algo = pareto_optimal.FastParetoOptimalAlgorithm(
base_algorithm=pareto_optimal.NaiveParetoOptimalAlgorithm(),
recursive_threshold=100)
... | # Generate points on positive orthant sphere.
points = abs(np.random.normal(size=(1000, 3)))
points /= np.linalg.norm(points, axis=1)[..., np.newaxis]
algo = pareto_optimal.FastParetoOptimalAlgorithm(
base_algorithm=pareto_optimal.NaiveParetoOptimalAlgorithm(),
recursive_threshold=100)
... | 22 | 971 | 144 | 1,115 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,067 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/multimetric/safety.py | 88,91 | 24,120 | warp_unsafe_trials | SafetyChecker | 100,120 | 91,120 | class SafetyChecker:
"""Returns the safety status of Measurements/Trials."""
def __init__(self, metrics_config: pyvizier.MetricsConfig):
"""Initializes with metric information (can have non-safety info).
Example usage from a study:
pyconfig = pyvizier.StudyConfig.from_proto(study.study_config)
... | class SafetyChecker:
"""Returns the safety status of Measurements/Trials."""
def __init__(self, metrics_config: pyvizier.MetricsConfig):
"""Initializes with metric information (can have non-safety info).
Example usage from a study:
pyconfig = pyvizier.StudyConfig.from_proto(study.study_config)
... | are_safe = self.are_trials_safe(trials)
objective_goals = {m.name: m.goal for m in self._objective_metrics}
for is_safe, trial in zip(are_safe, trials):
if is_safe:
continue
if trial.final_measurement is None:
continue
for name in trial.final_measurement.metrics.keys():
... | """Sets the final measurements of unsafe Trials to worst values in place.
Args:
trials: Sequence of pyvizier Trials.
Returns:
Trials whose final measurements are warped to the worst value (inf/-inf)
for all OBJECTIVE metrics in unsafe Trials.
"""
are_safe = self.are_trials_safe(t... | 51 | 843 | 224 | 1,067 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,068 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/multimetric/safety_test.py | 84,85 | 23,148 | testNoSafety | SafeAcquisitionTest | 85,105 | 85,105 | class SafeAcquisitionTest(absltest.TestCase):
def testSafeMeasurements(self):
info1 = pyvizier.MetricInformation(
name='safety1',
goal=pyvizier.ObjectiveMetricGoal.MAXIMIZE,
safety_threshold=0.1)
info2 = pyvizier.MetricInformation(
name='safety2',
goal=pyvizier.Objecti... | class SafeAcquisitionTest(absltest.TestCase):
def testSafeMeasurements(self):
info1 = pyvizier.MetricInformation(
name='safety1',
goal=pyvizier.ObjectiveMetricGoal.MAXIMIZE,
safety_threshold=0.1)
info2 = pyvizier.MetricInformation(
name='safety2',
goal=pyvizier.Objecti... | info1 = pyvizier.MetricInformation(
name='obj', goal=pyvizier.ObjectiveMetricGoal.MAXIMIZE)
checker = safety.SafetyChecker(pyvizier.MetricsConfig([info1]))
safe_trial = pyvizier.Trial(
final_measurement=pyvizier.Measurement(metrics={
'obj': 0.2,
'safety': 0.3
... | info1 = pyvizier.MetricInformation(
name='obj', goal=pyvizier.ObjectiveMetricGoal.MAXIMIZE)
checker = safety.SafetyChecker(pyvizier.MetricsConfig([info1]))
safe_trial = pyvizier.Trial(
final_measurement=pyvizier.Measurement(metrics={
'obj': 0.2,
'safety': 0.3
... | 42 | 1,385 | 270 | 1,655 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,069 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/oss/compare.py | 40,41 | 1,43 | assertProto2SameElements | 41,43 | 41,43 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | del args, kwargs
pass
| del args, kwargs
pass
| 4 | 336 | 13 | 349 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
47,071 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/base_study_config.py | 212,213 | 91,221 | flip_goal | MetricInformation | 214,221 | 213,221 | @attr.define(frozen=False, init=True, slots=True)
class MetricInformation:
"""MetricInformation provides optimization metrics configuration."""
# The name of this metric. An empty string is allowed for single-metric
# optimizations.
name: str = attr.field(
init=True, default='', validator=attr.validators... | @attr.define(frozen=False, init=True, slots=True)
class MetricInformation:
"""MetricInformation provides optimization metrics configuration."""
# The name of this metric. An empty string is allowed for single-metric
# optimizations.
name: str = attr.field(
init=True, default='', validator=attr.validators... | if self.goal == ObjectiveMetricGoal.MAXIMIZE:
self.goal = ObjectiveMetricGoal.MINIMIZE
else:
self.goal = ObjectiveMetricGoal.MAXIMIZE
return self
| """Flips the goal in-place and returns the reference to self."""
if self.goal == ObjectiveMetricGoal.MAXIMIZE:
self.goal = ObjectiveMetricGoal.MINIMIZE
else:
self.goal = ObjectiveMetricGoal.MAXIMIZE
return self
| 13 | 1,402 | 73 | 1,475 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,072 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/base_study_config.py | 82,84 | 71,91 | is_safety | MetricType | 84,86 | 84,86 | class MetricType(enum.Enum):
"""Type of the metric.
OBJECTIVE: Objective to be maximized / minimized.
SAFETY: Objective to be kept above / below a certain threshold.
"""
OBJECTIVE = 'OBJECTIVE'
SAFETY = 'SAFETY' # Soft constraint
# pylint: disable=comparison-with-callable
@property
def is_safety(s... | class MetricType(enum.Enum):
"""Type of the metric.
OBJECTIVE: Objective to be maximized / minimized.
SAFETY: Objective to be kept above / below a certain threshold.
"""
OBJECTIVE = 'OBJECTIVE'
SAFETY = 'SAFETY' # Soft constraint
# pylint: disable=comparison-with-callable
@property
def is_safety(s... | return self == MetricType.SAFETY
| return self == MetricType.SAFETY
| 4 | 163 | 15 | 178 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,073 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/base_study_config.py | 238,239 | 221,305 | item | MetricsConfig | 239,247 | 239,247 | @attr.define(frozen=False, init=True, slots=True)
class MetricsConfig(Collection[MetricInformation]):
"""Container for metrics.
Metric names should be unique.
"""
_metrics: List[MetricInformation] = attr.ib(
init=True,
factory=list,
converter=list,
validator=attr.validators.deep_iterab... | @attr.define(frozen=False, init=True, slots=True)
class MetricsConfig(Collection[MetricInformation]):
"""Container for metrics.
Metric names should be unique.
"""
_metrics: List[MetricInformation] = attr.ib(
init=True,
factory=list,
converter=list,
validator=attr.validators.deep_iterab... | if len(self._metrics) != 1:
raise ValueError(
'item() may only be called when there is exactly one '
'metric (there are %d).'
% len(self._metrics)
)
return self._metrics[0]
| if len(self._metrics) != 1:
raise ValueError(
'item() may only be called when there is exactly one '
'metric (there are %d).'
% len(self._metrics)
)
return self._metrics[0]
| 26 | 786 | 78 | 864 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,074 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/base_study_config.py | 66,68 | 55,71 | is_minimize | ObjectiveMetricGoal | 68,71 | 68,71 | class ObjectiveMetricGoal(enum.IntEnum):
"""Valid Values for MetricInformation.Goal."""
MAXIMIZE = 1
MINIMIZE = 2
# pylint: disable=comparison-with-callable
@property
def is_maximize(self) -> bool:
return self == self.MAXIMIZE
@property
def is_minimize(self) -> bool:
FILL_FUNC_BODY | class ObjectiveMetricGoal(enum.IntEnum):
"""Valid Values for MetricInformation.Goal."""
MAXIMIZE = 1
MINIMIZE = 2
# pylint: disable=comparison-with-callable
@property
def is_maximize(self) -> bool:
return self == self.MAXIMIZE
@property
def is_minimize(self) -> bool:
FILL_FUNC_BODY | return self == self.MINIMIZE
| return self == self.MINIMIZE
| 4 | 122 | 16 | 138 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,075 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/base_study_config.py | 348,350 | 305,406 | from_problem | ProblemStatement | 363,369 | 350,369 | @attr.define(frozen=False, init=True, slots=True)
class ProblemStatement:
"""Defines a blackbox optimization problem.
`ProblemStatement` contains the minimal information that defines the search
problem. It is inherited by platform-specific classes that carry additional
platform-specific configurations includin... | @attr.define(frozen=False, init=True, slots=True)
class ProblemStatement:
"""Defines a blackbox optimization problem.
`ProblemStatement` contains the minimal information that defines the search
problem. It is inherited by platform-specific classes that carry additional
platform-specific configurations includin... | return cls(
search_space=problem.search_space,
metric_information=problem.metric_information,
metadata=problem.metadata,
)
| """Converts a ProblemStatement to a subclass instance.
Note that this method is useful in subclasses but not so much in
`ProblemStatement` itself. `ProblemStatement.from_problem` simply generates
a (shallow) copy of `problem`.
Args:
problem:
Returns:
A subclass instance filled wit... | 6 | 950 | 48 | 998 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,076 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/base_study_config_test.py | 64,65 | 41,75 | testMinMaxBadValueSet | MetricInformationTest | 65,75 | 65,75 | class MetricInformationTest(absltest.TestCase):
def testMinMaxValueDefault(self):
info = base_study_config.MetricInformation(
goal=base_study_config.ObjectiveMetricGoal.MAXIMIZE)
self.assertEqual(info.min_value, -np.inf)
self.assertEqual(info.max_value, np.inf)
def testMinMaxValueSet(self):
... | class MetricInformationTest(absltest.TestCase):
def testMinMaxValueDefault(self):
info = base_study_config.MetricInformation(
goal=base_study_config.ObjectiveMetricGoal.MAXIMIZE)
self.assertEqual(info.min_value, -np.inf)
self.assertEqual(info.max_value, np.inf)
def testMinMaxValueSet(self):
... | info = base_study_config.MetricInformation(
goal=base_study_config.ObjectiveMetricGoal.MAXIMIZE,
min_value=-1.,
max_value=1.)
with self.assertRaises(ValueError):
info.min_value = 2.
with self.assertRaises(ValueError):
info.max_value = -2.
| info = base_study_config.MetricInformation(
goal=base_study_config.ObjectiveMetricGoal.MAXIMIZE,
min_value=-1.,
max_value=1.)
with self.assertRaises(ValueError):
info.min_value = 2.
with self.assertRaises(ValueError):
info.max_value = -2.
| 16 | 294 | 112 | 406 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,077 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/base_study_config_test.py | 36,37 | 34,41 | test_basics | MetricTypeTest | 37,41 | 37,41 | class MetricTypeTest(absltest.TestCase):
def test_basics(self):
FILL_FUNC_BODY | class MetricTypeTest(absltest.TestCase):
def test_basics(self):
FILL_FUNC_BODY | self.assertTrue(base_study_config.MetricType.SAFETY.is_safety)
self.assertTrue(base_study_config.MetricType.OBJECTIVE.is_objective)
| self.assertTrue(base_study_config.MetricType.SAFETY.is_safety)
self.assertTrue(base_study_config.MetricType.OBJECTIVE.is_objective)
| 2 | 34 | 61 | 95 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,078 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/base_study_config_test.py | 104,105 | 75,115 | testDuplicateNames | MetricsConfigTest | 105,115 | 105,115 | class MetricsConfigTest(parameterized.TestCase):
def testBasics(self):
config = base_study_config.MetricsConfig()
config.append(
base_study_config.MetricInformation(
name='max1', goal=base_study_config.ObjectiveMetricGoal.MAXIMIZE))
config.extend([
base_study_config.MetricInfo... | class MetricsConfigTest(parameterized.TestCase):
def testBasics(self):
config = base_study_config.MetricsConfig()
config.append(
base_study_config.MetricInformation(
name='max1', goal=base_study_config.ObjectiveMetricGoal.MAXIMIZE))
config.extend([
base_study_config.MetricInfo... | config = base_study_config.MetricsConfig()
config.append(
base_study_config.MetricInformation(
name='max1', goal=base_study_config.ObjectiveMetricGoal.MAXIMIZE))
with self.assertRaises(ValueError):
config.append(
base_study_config.MetricInformation(
name='ma... | config = base_study_config.MetricsConfig()
config.append(
base_study_config.MetricInformation(
name='max1', goal=base_study_config.ObjectiveMetricGoal.MAXIMIZE))
with self.assertRaises(ValueError):
config.append(
base_study_config.MetricInformation(
name='ma... | 13 | 441 | 134 | 575 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,079 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/base_study_config_test.py | 27,28 | 25,34 | test_basics | ObjectiveMetricGoalTest | 28,34 | 28,34 | class ObjectiveMetricGoalTest(absltest.TestCase):
def test_basics(self):
FILL_FUNC_BODY | class ObjectiveMetricGoalTest(absltest.TestCase):
def test_basics(self):
FILL_FUNC_BODY | self.assertTrue(base_study_config.ObjectiveMetricGoal.MAXIMIZE.is_maximize)
self.assertFalse(base_study_config.ObjectiveMetricGoal.MAXIMIZE.is_minimize)
self.assertTrue(base_study_config.ObjectiveMetricGoal.MINIMIZE.is_minimize)
self.assertFalse(base_study_config.ObjectiveMetricGoal.MINIMIZE.is_maximize... | self.assertTrue(base_study_config.ObjectiveMetricGoal.MAXIMIZE.is_maximize)
self.assertFalse(base_study_config.ObjectiveMetricGoal.MAXIMIZE.is_minimize)
self.assertTrue(base_study_config.ObjectiveMetricGoal.MINIMIZE.is_minimize)
self.assertFalse(base_study_config.ObjectiveMetricGoal.MINIMIZE.is_maximize... | 4 | 37 | 136 | 173 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,080 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/context_test.py | 25,26 | 23,33 | testDefaultsNotShared | ContextTest | 27,33 | 26,33 | class ContextTest(absltest.TestCase):
def testDefaultsNotShared(self):
FILL_FUNC_BODY | class ContextTest(absltest.TestCase):
def testDefaultsNotShared(self):
"""Make sure default parameters are not shared between instances."""
FILL_FUNC_BODY | context1 = context.Context()
context2 = context.Context()
context1.parameters['x1'] = context.ParameterValue(5)
self.assertEmpty(context2.parameters)
| """Make sure default parameters are not shared between instances."""
context1 = context.Context()
context2 = context.Context()
context1.parameters['x1'] = context.ParameterValue(5)
self.assertEmpty(context2.parameters)
| 10 | 46 | 56 | 102 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,081 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/parameter_config_test.py | 564,565 | 562,580 | testFlattenAndMerge | FlattenAndMergeTest | 565,580 | 565,580 | class FlattenAndMergeTest(absltest.TestCase):
def testFlattenAndMerge(self):
FILL_FUNC_BODY | class FlattenAndMergeTest(absltest.TestCase):
def testFlattenAndMerge(self):
FILL_FUNC_BODY | space = test_studies.conditional_automl_space()
parameters = space.root.select_all().merge()
logging.info('Merged: %s', parameters)
self.assertCountEqual(
[p.name for p in parameters],
[
'model_type',
'learning_rate',
'optimizer_type',
'use... | space = test_studies.conditional_automl_space()
parameters = space.root.select_all().merge()
logging.info('Merged: %s', parameters)
self.assertCountEqual(
[p.name for p in parameters],
[
'model_type',
'learning_rate',
'optimizer_type',
'use... | 23 | 39 | 131 | 170 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,082 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/parameter_config_test.py | 226,227 | 224,252 | test_merge_bounds | MergeTest | 227,233 | 227,233 | class MergeTest(parameterized.TestCase):
def test_merge_bounds(self):
FILL_FUNC_BODY def test_merge_discrete(self):
pc1 = pc.ParameterConfig.factory(
'pc1', feasible_values=[0.0, 2.0], scale_type=pc.ScaleType.LINEAR)
pc2 = pc.ParameterConfig.factory('pc2', feasible_values=[-1.0, 0.0])
self.asser... | class MergeTest(parameterized.TestCase):
def test_merge_bounds(self):
FILL_FUNC_BODY def test_merge_discrete(self):
pc1 = pc.ParameterConfig.factory(
'pc1', feasible_values=[0.0, 2.0], scale_type=pc.ScaleType.LINEAR)
pc2 = pc.ParameterConfig.factory('pc2', feasible_values=[-1.0, 0.0])
self.asser... | pc1 = pc.ParameterConfig.factory('pc1', bounds=(0.0, 2.0))
pc2 = pc.ParameterConfig.factory('pc2', bounds=(-1.0, 1.0))
self.assertEqual(
pc.ParameterConfig.merge(pc1, pc2),
pc.ParameterConfig.factory('pc1', bounds=(-1.0, 2.0)))
| pc1 = pc.ParameterConfig.factory('pc1', bounds=(0.0, 2.0))
pc2 = pc.ParameterConfig.factory('pc2', bounds=(-1.0, 1.0))
self.assertEqual(
pc.ParameterConfig.merge(pc1, pc2),
pc.ParameterConfig.factory('pc1', bounds=(-1.0, 2.0)))
| 16 | 303 | 106 | 409 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,083 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/parameter_config_test.py | 269,271 | 252,282 | testCategorical | ParameterConfigContainsTest | 271,275 | 271,275 | class ParameterConfigContainsTest(parameterized.TestCase):
@parameterized.parameters((1.0, True), (-2.0, False), (3.0, False))
def testFloat(self, value: Any, expected: bool):
config = pc.ParameterConfig.factory('pc1', bounds=(-1., 2.))
self.assertEqual(config.contains(value), expected)
@parameterized.p... | class ParameterConfigContainsTest(parameterized.TestCase):
@parameterized.parameters((1.0, True), (-2.0, False), (3.0, False))
def testFloat(self, value: Any, expected: bool):
config = pc.ParameterConfig.factory('pc1', bounds=(-1., 2.))
self.assertEqual(config.contains(value), expected)
@parameterized.p... | config = pc.ParameterConfig.factory(
'pc1', feasible_values=['a', 'aa', 'aaa'])
self.assertEqual(config.contains(value), expected)
| config = pc.ParameterConfig.factory(
'pc1', feasible_values=['a', 'aa', 'aaa'])
self.assertEqual(config.contains(value), expected)
| 9 | 402 | 50 | 452 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,084 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/parameter_config_test.py | 32,33 | 30,170 | testCreatesDoubleConfig | ParameterConfigFactoryTest | 33,49 | 33,49 | class ParameterConfigFactoryTest(parameterized.TestCase):
def testCreatesDoubleConfig(self):
FILL_FUNC_BODY def testCreatesIntegerConfig(self):
parameter_config = pc.ParameterConfig.factory(
'name', bounds=(1, 3), scale_type=pc.ScaleType.LOG, default_value=1)
self.assertEqual(parameter_config.name, ... | class ParameterConfigFactoryTest(parameterized.TestCase):
def testCreatesDoubleConfig(self):
FILL_FUNC_BODY def testCreatesIntegerConfig(self):
parameter_config = pc.ParameterConfig.factory(
'name', bounds=(1, 3), scale_type=pc.ScaleType.LOG, default_value=1)
self.assertEqual(parameter_config.name, ... | parameter_config = pc.ParameterConfig.factory(
'name',
bounds=(-1.0, 1.0),
scale_type=pc.ScaleType.LINEAR,
default_value=0.1)
self.assertEqual(parameter_config.name, 'name')
self.assertEqual(parameter_config.type, pc.ParameterType.DOUBLE)
self.assertEqual(parameter_config... | parameter_config = pc.ParameterConfig.factory(
'name',
bounds=(-1.0, 1.0),
scale_type=pc.ScaleType.LINEAR,
default_value=0.1)
self.assertEqual(parameter_config.name, 'name')
self.assertEqual(parameter_config.type, pc.ParameterType.DOUBLE)
self.assertEqual(parameter_config... | 28 | 1,689 | 230 | 1,919 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,085 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/parameter_config_test.py | 191,195 | 174,224 | testDiscreteWithValid | ParameterConfigFactoryTestWithChildren | 195,200 | 195,200 | class ParameterConfigFactoryTestWithChildren(parameterized.TestCase):
@parameterized.named_parameters(
('IntParentValues', [([0], _child1), ([0, 1], _child2)]),
('FloatParentValues', [([0.0], _child1), ([0.0, 1.0], _child2)]))
def testIntegerWithValid(self, children):
p = pc.ParameterConfig.factory... | class ParameterConfigFactoryTestWithChildren(parameterized.TestCase):
@parameterized.named_parameters(
('IntParentValues', [([0], _child1), ([0, 1], _child2)]),
('FloatParentValues', [([0.0], _child1), ([0.0, 1.0], _child2)]))
def testIntegerWithValid(self, children):
p = pc.ParameterConfig.factory... | p = pc.ParameterConfig.factory(
'parent', feasible_values=[0.0, 1.0], children=children)
self.assertCountEqual(p.subspace(0.0).parameters, [_child1, _child2])
self.assertCountEqual(p.subspace(1.0).parameters, [_child2])
| p = pc.ParameterConfig.factory(
'parent', feasible_values=[0.0, 1.0], children=children)
self.assertCountEqual(p.subspace(0.0).parameters, [_child1, _child2])
self.assertCountEqual(p.subspace(1.0).parameters, [_child2])
| 12 | 714 | 90 | 804 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,086 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/parameter_config_test.py | 295,299 | 282,307 | testDiscreteandCategorical | ParameterConfigPropertyTest | 299,307 | 299,307 | class ParameterConfigPropertyTest(parameterized.TestCase):
@parameterized.parameters(
((-1.0, 1.0), None), ((-1, 1), None), ((-2.0, -2.0), -2.0), ((-2, -2), -2)
)
def testFloatandInt(self, bounds: Any, expected: Any):
config = pc.ParameterConfig.factory('pc1', bounds=bounds)
value = config.determin... | class ParameterConfigPropertyTest(parameterized.TestCase):
@parameterized.parameters(
((-1.0, 1.0), None), ((-1, 1), None), ((-2.0, -2.0), -2.0), ((-2, -2), -2)
)
def testFloatandInt(self, bounds: Any, expected: Any):
config = pc.ParameterConfig.factory('pc1', bounds=bounds)
value = config.determin... | config = pc.ParameterConfig.factory('pc1', feasible_values=feasible_values)
value = config.deterministic_value
if expected is None:
self.assertIsNone(value)
else:
self.assertEqual(value, expected)
| config = pc.ParameterConfig.factory('pc1', feasible_values=feasible_values)
value = config.deterministic_value
if expected is None:
self.assertIsNone(value)
else:
self.assertEqual(value, expected)
| 15 | 241 | 76 | 317 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,088 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/parameter_config_test.py | 596,597 | 580,619 | testFloatCat2 | SearchSpaceContainsTest | 597,603 | 597,603 | class SearchSpaceContainsTest(absltest.TestCase):
def _space(self):
space = pc.SearchSpace()
root = space.select_root()
root.add_float_param('learning-rate', 1e-4, 1e-2)
root.add_categorical_param('optimizer', ['adagrad', 'adam', 'experimental'])
return space
def testFloatCat1(self):
self.... | class SearchSpaceContainsTest(absltest.TestCase):
def _space(self):
space = pc.SearchSpace()
root = space.select_root()
root.add_float_param('learning-rate', 1e-4, 1e-2)
root.add_categorical_param('optimizer', ['adagrad', 'adam', 'experimental'])
return space
def testFloatCat1(self):
self.... | self.assertFalse(self._space().contains(
trial.ParameterDict({
'optimizer': 'adagrad',
'BADPARAM': 1e-2
})))
| self.assertFalse(self._space().contains(
trial.ParameterDict({
'optimizer': 'adagrad',
'BADPARAM': 1e-2
})))
| 7 | 307 | 55 | 362 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,089 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/parameter_config_test.py | 335,336 | 332,365 | testRootAndSelectRootEqual | SearchSpaceTest | 336,341 | 336,341 | class SearchSpaceTest(parameterized.TestCase):
"""Check basic functionalities."""
def testRootAndSelectRootEqual(self):
FILL_FUNC_BODY def testAddFloatParamMinimal(self):
# Remove this test once we deprecate select_root().
space = pc.SearchSpace()
self.assertEmpty(space.parameters)
_ = space.selec... | class SearchSpaceTest(parameterized.TestCase):
"""Check basic functionalities."""
def testRootAndSelectRootEqual(self):
FILL_FUNC_BODY def testAddFloatParamMinimal(self):
# Remove this test once we deprecate select_root().
space = pc.SearchSpace()
self.assertEmpty(space.parameters)
_ = space.selec... | space = pc.SearchSpace()
select_root = space.select_root()
shortcut_root = space.root
self.assertIs(select_root._selected[0], shortcut_root._selected[0])
| space = pc.SearchSpace()
select_root = space.select_root()
shortcut_root = space.root
self.assertIs(select_root._selected[0], shortcut_root._selected[0])
| 11 | 355 | 59 | 414 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,090 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/parameter_config_test.py | 309,312 | 307,332 | testTraverse | TraverseTest | 312,332 | 312,332 | class TraverseTest(parameterized.TestCase):
@parameterized.named_parameters(('ShowChildrenTrue', True),
('ShowChildrenFalse', False))
def testTraverse(self, show_children):
FILL_FUNC_BODY | class TraverseTest(parameterized.TestCase):
@parameterized.named_parameters(('ShowChildrenTrue', True),
('ShowChildrenFalse', False))
def testTraverse(self, show_children):
FILL_FUNC_BODY | grandchild1 = pc.ParameterConfig.factory('grandchild1', bounds=(-1.0, 1.0))
grandchildren = [(['a'], grandchild1), (['b'], grandchild1)]
child1 = pc.ParameterConfig.factory(
'child1', feasible_values=['a', 'b'], children=grandchildren)
child2 = pc.ParameterConfig.factory('child2', bounds=(0.0, ... | grandchild1 = pc.ParameterConfig.factory('grandchild1', bounds=(-1.0, 1.0))
grandchildren = [(['a'], grandchild1), (['b'], grandchild1)]
child1 = pc.ParameterConfig.factory(
'child1', feasible_values=['a', 'b'], children=grandchildren)
child2 = pc.ParameterConfig.factory('child2', bounds=(0.0, ... | 77 | 61 | 304 | 365 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,091 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/parameter_iterators.py | 66,69 | 29,119 | _coroutine | SequentialParameterBuilder | 69,93 | 69,93 | class SequentialParameterBuilder(Iterator[ParameterConfig]):
"""Builds a ParameterDict by choosing one parameter value at a time.
Example usage:
from vizier import pyvizier as vz
def decide_value(pc: vz.ParameterConfig) -> vz.ParameterValueTypes:
...
search_space : vz.SearchSpace
builder = ... | class SequentialParameterBuilder(Iterator[ParameterConfig]):
"""Builds a ParameterDict by choosing one parameter value at a time.
Example usage:
from vizier import pyvizier as vz
def decide_value(pc: vz.ParameterConfig) -> vz.ParameterValueTypes:
...
search_space : vz.SearchSpace
builder = ... | search_space = copy.deepcopy(search_space)
while search_space.parameters:
parameter_config = search_space.parameters[0]
value = yield parameter_config
if value is None:
search_space.pop(parameter_config.name)
continue
# Note: get_subspace also validates the value.
s... | search_space = copy.deepcopy(search_space)
while search_space.parameters:
parameter_config = search_space.parameters[0]
value = yield parameter_config
if value is None:
search_space.pop(parameter_config.name)
continue
# Note: get_subspace also validates the value.
s... | 74 | 596 | 268 | 864 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,092 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/parameter_iterators_test.py | 31,44 | 29,69 | test_e2e | ParameterIteratorsTest | 44,69 | 44,69 | class ParameterIteratorsTest(parameterized.TestCase):
@parameterized.parameters(
dict(
traverse_order='bfs',
expected_order=[
'model', 'apply_preprocessing', 'num_layers', 'preprocessor'
]),
dict(
traverse_order='dfs',
expected_order=[
... | class ParameterIteratorsTest(parameterized.TestCase):
@parameterized.parameters(
dict(
traverse_order='bfs',
expected_order=[
'model', 'apply_preprocessing', 'num_layers', 'preprocessor'
]),
dict(
traverse_order='dfs',
expected_order=[
... | valid_params = {
'model': 'dnn',
'apply_preprocessing': True,
'preprocessor': 'augment',
'num_layers': 1, # child parameter comes last.
}
valid_params = {k: valid_params[k] for k in expected_order}
space = vz.SearchSpace()
model = space.root.add_categorical_param('m... | valid_params = {
'model': 'dnn',
'apply_preprocessing': True,
'preprocessor': 'augment',
'num_layers': 1, # child parameter comes last.
}
valid_params = {k: valid_params[k] for k in expected_order}
space = vz.SearchSpace()
model = space.root.add_categorical_param('m... | 58 | 162 | 334 | 496 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,093 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/trial_test.py | 49,50 | 47,67 | testMetricsInitializedFromFloats | MeasurementTest | 50,56 | 50,56 | class MeasurementTest(absltest.TestCase):
def testMetricsInitializedFromFloats(self):
FILL_FUNC_BODY def testMetrics(self):
m = Measurement()
m.metrics = dict(a=Metric(0.3))
self.assertEqual(m.metrics['a'], Metric(0.3))
def testTimeStampsAreNotFrozen(self):
m = Measurement()
m.elapsed_secs = ... | class MeasurementTest(absltest.TestCase):
def testMetricsInitializedFromFloats(self):
FILL_FUNC_BODY def testMetrics(self):
m = Measurement()
m.metrics = dict(a=Metric(0.3))
self.assertEqual(m.metrics['a'], Metric(0.3))
def testTimeStampsAreNotFrozen(self):
m = Measurement()
m.elapsed_secs = ... | m = Measurement()
m.metrics = dict(a=0.3)
self.assertEqual(m.metrics['a'], Metric(0.3))
m.metrics['b'] = 0.5
self.assertEqual(m.metrics, {'a': Metric(0.3), 'b': Metric(0.5)})
| m = Measurement()
m.metrics = dict(a=0.3)
self.assertEqual(m.metrics['a'], Metric(0.3))
m.metrics['b'] = 0.5
self.assertEqual(m.metrics, {'a': Metric(0.3), 'b': Metric(0.5)})
| 16 | 137 | 94 | 231 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,094 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/trial_test.py | 35,36 | 33,47 | testMetricCreation | MetricTest | 36,38 | 36,38 | class MetricTest(absltest.TestCase):
def testMetricCreation(self):
FILL_FUNC_BODY def testMetricCannotHaveNaN(self):
with self.assertRaises(ValueError):
_ = Metric(value=np.nan, std=-np.nan)
def testMetricCannotHaveNegativeStd(self):
with self.assertRaises(ValueError):
_ = Metric(value=0, std... | class MetricTest(absltest.TestCase):
def testMetricCreation(self):
FILL_FUNC_BODY def testMetricCannotHaveNaN(self):
with self.assertRaises(ValueError):
_ = Metric(value=np.nan, std=-np.nan)
def testMetricCannotHaveNegativeStd(self):
with self.assertRaises(ValueError):
_ = Metric(value=0, std... | _ = Metric(value=0, std=0.5)
| _ = Metric(value=0, std=0.5)
| 4 | 127 | 20 | 147 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,095 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/trial_test.py | 339,341 | 327,351 | testAssignWrappedValue | ParameterDictTest | 341,351 | 341,351 | class ParameterDictTest(parameterized.TestCase):
@parameterized.parameters((True,), (3,), (1.,), ('aa',))
def testAssignRawValue(self, v):
d = trial.ParameterDict()
d['p1'] = v
self.assertEqual(d.get('p1'), trial.ParameterValue(v))
self.assertEqual(d.get_value('p1'), v)
self.assertEqual(d.get_v... | class ParameterDictTest(parameterized.TestCase):
@parameterized.parameters((True,), (3,), (1.,), ('aa',))
def testAssignRawValue(self, v):
d = trial.ParameterDict()
d['p1'] = v
self.assertEqual(d.get('p1'), trial.ParameterValue(v))
self.assertEqual(d.get_value('p1'), v)
self.assertEqual(d.get_v... | d = trial.ParameterDict()
v = trial.ParameterValue(v)
d['p1'] = v
self.assertEqual(d.get('p1'), v)
self.assertEqual(d.get_value('p1'), v.value)
self.assertEqual(d.get_value('p2', 'default'), 'default')
self.assertLen(d, 1)
self.assertLen(d.items(), 1)
| d = trial.ParameterDict()
v = trial.ParameterValue(v)
d['p1'] = v
self.assertEqual(d.get('p1'), v)
self.assertEqual(d.get_value('p1'), v.value)
self.assertEqual(d.get_value('p2', 'default'), 'default')
self.assertLen(d, 1)
self.assertLen(d.items(), 1)
| 20 | 201 | 123 | 324 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,096 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/trial_test.py | 138,139 | 70,151 | testStringInt1 | ParameterValueTest | 139,145 | 139,145 | class ParameterValueTest(parameterized.TestCase):
@parameterized.parameters((True,), (False,))
def testBool(self, bool_value):
value = ParameterValue(bool_value)
self.assertEqual(value.as_float, float(bool_value))
self.assertEqual(value.as_int, int(bool_value))
self.assertEqual(value.as_str, str(bo... | class ParameterValueTest(parameterized.TestCase):
@parameterized.parameters((True,), (False,))
def testBool(self, bool_value):
value = ParameterValue(bool_value)
self.assertEqual(value.as_float, float(bool_value))
self.assertEqual(value.as_int, int(bool_value))
self.assertEqual(value.as_str, str(bo... | value = ParameterValue('1')
self.assertEqual(value.as_float, 1.0)
self.assertEqual(value.as_int, 1)
self.assertIsNone(value.as_bool)
self.assertEqual(value.as_str, '1')
| value = ParameterValue('1')
self.assertEqual(value.as_float, 1.0)
self.assertEqual(value.as_int, 1)
self.assertIsNone(value.as_bool)
self.assertEqual(value.as_str, '1')
| 10 | 874 | 78 | 952 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,097 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/trial_test.py | 353,354 | 351,363 | testToTrial | SuggestionTestI | 354,363 | 354,363 | class SuggestionTestI(absltest.TestCase):
def testToTrial(self):
FILL_FUNC_BODY | class SuggestionTestI(absltest.TestCase):
def testToTrial(self):
FILL_FUNC_BODY | suggestion = trial.TrialSuggestion({'a': 3, 'b': True})
suggestion.metadata['key'] = 'value'
t = suggestion.to_trial(1)
self.assertEqual(t.id, 1)
self.assertEqual(t.parameters, suggestion.parameters)
self.assertEqual(t.metadata, suggestion.metadata)
| suggestion = trial.TrialSuggestion({'a': 3, 'b': True})
suggestion.metadata['key'] = 'value'
t = suggestion.to_trial(1)
self.assertEqual(t.id, 1)
self.assertEqual(t.parameters, suggestion.parameters)
self.assertEqual(t.metadata, suggestion.metadata)
| 18 | 35 | 101 | 136 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,098 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/pyvizier/shared/trial_test.py | 365,381 | 363,390 | test_filter | TrialFilterTest | 381,390 | 381,390 | class TrialFilterTest(parameterized.TestCase):
@parameterized.parameters(
dict(filtr=trial.TrialFilter(), answers=[True, True, True, True]),
dict(
filtr=trial.TrialFilter(ids=(2, 3)),
answers=[False, True, True, False]),
dict(
filtr=trial.TrialFilter(min_id=3, ids=(2, ... | class TrialFilterTest(parameterized.TestCase):
@parameterized.parameters(
dict(filtr=trial.TrialFilter(), answers=[True, True, True, True]),
dict(
filtr=trial.TrialFilter(ids=(2, 3)),
answers=[False, True, True, False]),
dict(
filtr=trial.TrialFilter(min_id=3, ids=(2, ... | trials = (
trial.Trial(id=1), # ACTIVE
trial.Trial(id=2, is_requested=True), # REQUESTED
trial.Trial(id=3, stopping_reason='stopping'), # STOPPING
trial.Trial(id=4).complete(trial.Measurement()), # COMPLETED
)
self.assertSequenceEqual([filtr(t) for t in trials], answers)... | trials = (
trial.Trial(id=1), # ACTIVE
trial.Trial(id=2, is_requested=True), # REQUESTED
trial.Trial(id=3, stopping_reason='stopping'), # STOPPING
trial.Trial(id=4).complete(trial.Measurement()), # COMPLETED
)
self.assertSequenceEqual([filtr(t) for t in trials], answers)... | 24 | 240 | 128 | 368 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,100 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/clients.py | 203,204 | 124,266 | materialize_state | Study | 204,206 | 204,206 | @attr.define
class Study(client_abc.StudyInterface):
"""Responsible for study-level operations."""
_client: vizier_client.VizierClient = attr.field()
@property
def resource_name(self) -> str:
return self._client.study_resource_name
def _trial_client(self, trial: vz.Trial) -> Trial:
"""Returns the c... | @attr.define
class Study(client_abc.StudyInterface):
"""Responsible for study-level operations."""
_client: vizier_client.VizierClient = attr.field()
@property
def resource_name(self) -> str:
return self._client.study_resource_name
def _trial_client(self, trial: vz.Trial) -> Trial:
"""Returns the c... | return self._client.get_study_state()
| return self._client.get_study_state()
| 2 | 1,462 | 17 | 1,479 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,101 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/clients.py | 100,102 | 37,105 | study | Trial | 102,105 | 102,105 | @attr.define
class Trial(client_abc.TrialInterface):
"""Trial class.
This class owns a Vizier client of the Study that contains the Trial that
it is associated with.
"""
_client: vizier_client.VizierClient = attr.field()
_id: int = attr.field(validator=attr.validators.instance_of(int))
@property
def ... | @attr.define
class Trial(client_abc.TrialInterface):
"""Trial class.
This class owns a Vizier client of the Study that contains the Trial that
it is associated with.
"""
_client: vizier_client.VizierClient = attr.field()
_id: int = attr.field(validator=attr.validators.instance_of(int))
@property
def ... | return Study(self._client)
| return Study(self._client)
| 2 | 657 | 14 | 671 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,102 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/clients.py | 119,120 | 105,124 | get | TrialIterable | 120,124 | 120,124 | @attr.define
class TrialIterable(client_abc.TrialIterable):
"""Holds a collection of materialized Trials.
See the parent class for full pydocs.
"""
_iterable_factory: Callable[[], Iterable[vz.Trial]] = attr.field()
_client: vizier_client.VizierClient = attr.field()
def __iter__(self) -> Iterator[Trial]:
... | @attr.define
class TrialIterable(client_abc.TrialIterable):
"""Holds a collection of materialized Trials.
See the parent class for full pydocs.
"""
_iterable_factory: Callable[[], Iterable[vz.Trial]] = attr.field()
_client: vizier_client.VizierClient = attr.field()
def __iter__(self) -> Iterator[Trial]:
... | for trial in self._iterable_factory():
yield trial
| for trial in self._iterable_factory():
yield trial
| 6 | 169 | 22 | 191 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,103 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/clients_test.py | 50,51 | 34,65 | test_e2e_tuning_gp | VizierClientTest | 51,65 | 51,65 | class VizierClientTest(client_abc_testing.TestCase):
_owner: str
def create_study(
self, problem: vz.ProblemStatement, study_id: str
) -> clients.Study:
config = vz.StudyConfig.from_problem(problem)
config.algorithm = vz.Algorithm.RANDOM_SEARCH
study = clients.Study.from_study_config(
c... | class VizierClientTest(client_abc_testing.TestCase):
_owner: str
def create_study(
self, problem: vz.ProblemStatement, study_id: str
) -> clients.Study:
config = vz.StudyConfig.from_problem(problem)
config.algorithm = vz.Algorithm.RANDOM_SEARCH
study = clients.Study.from_study_config(
c... | def create_study(
problem: vz.ProblemStatement, study_id: str
) -> clients.Study:
config = vz.StudyConfig.from_problem(problem)
config.algorithm = vz.Algorithm.GAUSSIAN_PROCESS_BANDIT
study = clients.Study.from_study_config(
config, owner='owner', study_id=study_id
)
... | def create_study(
problem: vz.ProblemStatement, study_id: str
) -> clients.Study:
config = vz.StudyConfig.from_problem(problem)
config.algorithm = vz.Algorithm.GAUSSIAN_PROCESS_BANDIT
study = clients.Study.from_study_config(
config, owner='owner', study_id=study_id
)
... | 30 | 188 | 185 | 373 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,104 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/clients_test.py | 78,80 | 75,94 | setUpClass | VizierClientTestOnDefaultServer | 80,88 | 80,88 | class VizierClientTestOnDefaultServer(VizierClientTest):
_server: vizier_server.DefaultVizierServer
@classmethod
def setUpClass(cls):
FILL_FUNC_BODY @classmethod
def tearDownClass(cls):
cls._server._server.stop(None)
super().tearDownClass()
| class VizierClientTestOnDefaultServer(VizierClientTest):
_server: vizier_server.DefaultVizierServer
@classmethod
def setUpClass(cls):
FILL_FUNC_BODY @classmethod
def tearDownClass(cls):
cls._server._server.stop(None)
super().tearDownClass()
| logging.info('Test setup started.')
super().setUpClass()
cls._server = vizier_server.DefaultVizierServer(
database_url=constants.SQL_MEMORY_URL
)
clients.environment_variables.server_endpoint = cls._server.endpoint
logging.info('Test setup finished.')
| logging.info('Test setup started.')
super().setUpClass()
cls._server = vizier_server.DefaultVizierServer(
database_url=constants.SQL_MEMORY_URL
)
clients.environment_variables.server_endpoint = cls._server.endpoint
logging.info('Test setup finished.')
| 15 | 96 | 97 | 193 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,105 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/clients_test.py | 97,99 | 94,114 | setUpClass | VizierClientTestOnDistributedPythiaServer | 99,107 | 99,107 | class VizierClientTestOnDistributedPythiaServer(VizierClientTest):
_server: vizier_server.DistributedPythiaVizierServer
@classmethod
def setUpClass(cls):
FILL_FUNC_BODY @classmethod
def tearDownClass(cls):
cls._server._server.stop(None)
cls._server._pythia_server.stop(None)
super().tearDownClass()... | class VizierClientTestOnDistributedPythiaServer(VizierClientTest):
_server: vizier_server.DistributedPythiaVizierServer
@classmethod
def setUpClass(cls):
FILL_FUNC_BODY @classmethod
def tearDownClass(cls):
cls._server._server.stop(None)
cls._server._pythia_server.stop(None)
super().tearDownClass()... | logging.info('Test setup started.')
super().setUpClass()
cls._server = vizier_server.DistributedPythiaVizierServer(
database_url=constants.SQL_MEMORY_URL
)
clients.environment_variables.server_endpoint = cls._server.endpoint
logging.info('Test setup finished.')
| logging.info('Test setup started.')
super().setUpClass()
cls._server = vizier_server.DistributedPythiaVizierServer(
database_url=constants.SQL_MEMORY_URL
)
clients.environment_variables.server_endpoint = cls._server.endpoint
logging.info('Test setup finished.')
| 15 | 121 | 101 | 222 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,106 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/clients_test.py | 67,69 | 65,75 | setUpClass | VizierClientTestOnServicer | 69,75 | 69,75 | class VizierClientTestOnServicer(VizierClientTest):
@classmethod
def setUpClass(cls):
FILL_FUNC_BODY | class VizierClientTestOnServicer(VizierClientTest):
@classmethod
def setUpClass(cls):
FILL_FUNC_BODY | logging.info('Test setup started.')
super().setUpClass()
clients.environment_variables.server_endpoint = constants.NO_ENDPOINT
logging.info('Test setup finished.')
| logging.info('Test setup started.')
super().setUpClass()
clients.environment_variables.server_endpoint = constants.NO_ENDPOINT
logging.info('Test setup finished.')
| 10 | 43 | 59 | 102 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,107 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/grpc_util.py | 45,48 | 1,89 | handle_exception | 71,89 | 48,89 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | if context is None:
context = LocalRpcError(e)
if isinstance(
e, (custom_errors.ImmutableStudyError, custom_errors.ImmutableTrialError)
):
context.set_code(grpc.StatusCode.FAILED_PRECONDITION)
elif isinstance(e, custom_errors.NotFoundError):
context.set_code(grpc.StatusCode.NOT_FOUND)
elif ... | """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
collec... | 30 | 709 | 221 | 930 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
47,108 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/grpc_util.py | 40,41 | 25,45 | details | LocalRpcError | 41,45 | 41,45 | class LocalRpcError(grpc.RpcError):
"""Class for imitating both a `grpc.ServiceContext` and a `grpc.RpcError`."""
_code: grpc.StatusCode = grpc.StatusCode.UNKNOWN
_details: Optional[str] = None
def set_code(self, code: grpc.StatusCode) -> None:
self._code = code
def set_details(self, details: str) -> N... | class LocalRpcError(grpc.RpcError):
"""Class for imitating both a `grpc.ServiceContext` and a `grpc.RpcError`."""
_code: grpc.StatusCode = grpc.StatusCode.UNKNOWN
_details: Optional[str] = None
def set_code(self, code: grpc.StatusCode) -> None:
self._code = code
def set_details(self, details: str) -> N... | return self._details
# TODO: Use this for all service errors.
| return self._details
# TODO: Use this for all service errors.
| 10 | 175 | 23 | 198 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,109 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/performance_test.py | 44,54 | 33,100 | test_multiple_clients_basic | PerformanceTest | 54,100 | 54,100 | class PerformanceTest(parameterized.TestCase):
server: vizier_server.DefaultVizierServer
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.server = vizier_server.DefaultVizierServer(
database_url=constants.SQL_MEMORY_URL
)
vizier_client.environment_variables.server_endpoint = cls... | class PerformanceTest(parameterized.TestCase):
server: vizier_server.DefaultVizierServer
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.server = vizier_server.DefaultVizierServer(
database_url=constants.SQL_MEMORY_URL
)
vizier_client.environment_variables.server_endpoint = cls... | def fn(client_id: int):
experimenter = experimenters.BBOBExperimenterFactory(
'Sphere', dimension
)()
problem_statement = experimenter.problem_statement()
study_config = pyvizier.StudyConfig.from_problem(problem_statement)
study_config.algorithm = pyvizier.Algorithm.NSGA2
... | def fn(client_id: int):
experimenter = experimenters.BBOBExperimenterFactory(
'Sphere', dimension
)()
problem_statement = experimenter.problem_statement()
study_config = pyvizier.StudyConfig.from_problem(problem_statement)
study_config.algorithm = pyvizier.Algorithm.NSGA2
... | 96 | 234 | 495 | 729 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,110 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/pythia_util.py | 64,65 | 32,86 | WaitForResponse | ResponseWaiter | 71,82 | 65,82 | class ResponseWaiter(Generic[_T]):
"""A stored message with a Wait() mechanism.
This is a bridge between two threads; it stores a message, and
the reader thread waits until the writer thread calls Report(..., done=True).
Once Report() is called, it unblocks WaitForRespose().
"""
def __init__(self):
se... | class ResponseWaiter(Generic[_T]):
"""A stored message with a Wait() mechanism.
This is a bridge between two threads; it stores a message, and
the reader thread waits until the writer thread calls Report(..., done=True).
Once Report() is called, it unblocks WaitForRespose().
"""
def __init__(self):
se... | self._wait.wait()
logging.info('About to take _lock in ResponseWaiter.WaitForResponse()')
with self._lock:
if self._response is None:
logging.info('Raise')
raise pythia.PythiaProtocolError('No response.')
elif self._response.error_details:
raise pythia.VizierDatabaseError... | """Returns the result or raises an error.
Raises:
PythiaProtocolError: Due to a failure of the Pythia protocol.
VizierDatabaseError: Vizier was unable to service the request.
"""
self._wait.wait()
logging.info('About to take _lock in ResponseWaiter.WaitForResponse()')
with self._loc... | 28 | 401 | 135 | 536 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,111 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/resources.py | 175,177 | 153,198 | from_name | EarlyStoppingOperationResource | 178,191 | 177,191 | @attr.define(init=True, frozen=True)
class EarlyStoppingOperationResource:
"""Resource for Early Stopping Operations."""
owner_id: str = attr.ib(init=True, validator=_resource_component_validator)
study_id: str = attr.ib(init=True, validator=_resource_component_validator)
trial_id: int = attr.ib(
init=Tr... | @attr.define(init=True, frozen=True)
class EarlyStoppingOperationResource:
"""Resource for Early Stopping Operations."""
owner_id: str = attr.ib(init=True, validator=_resource_component_validator)
study_id: str = attr.ib(init=True, validator=_resource_component_validator)
trial_id: int = attr.ib(
init=Tr... | operation_match = re.match(
r'^owners\/(?P<owner_id>[^\/]+)/operations/earlystopping/(?P<study_id>[^\/]+)/(?P<trial_id>[^\/]+)$',
resource_name,
)
if operation_match:
return EarlyStoppingOperationResource(
operation_match.group('owner_id'),
operation_match.group('st... | """Creates EarlyStoppingOperationResource from a name."""
operation_match = re.match(
r'^owners\/(?P<owner_id>[^\/]+)/operations/earlystopping/(?P<study_id>[^\/]+)/(?P<trial_id>[^\/]+)$',
resource_name,
)
if operation_match:
return EarlyStoppingOperationResource(
operatio... | 21 | 333 | 176 | 509 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,112 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/resources.py | 43,45 | 37,61 | from_name | OwnerResource | 45,52 | 45,52 | @attr.define(init=True, frozen=True)
class OwnerResource:
"""Resource for Owners."""
_owner_id: str = attr.ib(init=True, validator=_resource_component_validator)
@classmethod
def from_name(cls, resource_name: str):
FILL_FUNC_BODY @property
def owner_id(self):
return self._owner_id
@property
def na... | @attr.define(init=True, frozen=True)
class OwnerResource:
"""Resource for Owners."""
_owner_id: str = attr.ib(init=True, validator=_resource_component_validator)
@classmethod
def from_name(cls, resource_name: str):
FILL_FUNC_BODY @property
def owner_id(self):
return self._owner_id
@property
def na... | owner_match = re.match(r'^owners\/(?P<owner_id>[^\/]+)$', resource_name)
if owner_match:
return OwnerResource(owner_id=owner_match.group('owner_id'))
else:
raise ValueError(f'Incorrect resource name sent: {resource_name}')
| owner_match = re.match(r'^owners\/(?P<owner_id>[^\/]+)$', resource_name)
if owner_match:
return OwnerResource(owner_id=owner_match.group('owner_id'))
else:
raise ValueError(f'Incorrect resource name sent: {resource_name}')
| 15 | 140 | 96 | 236 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,113 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/resources.py | 68,70 | 61,101 | from_name | StudyResource | 71,85 | 70,85 | @attr.define(init=True, frozen=True)
class StudyResource:
"""Resource for Studies."""
owner_id: str = attr.ib(init=True, validator=_resource_component_validator)
study_id: str = attr.ib(init=True, validator=_resource_component_validator)
@classmethod
def from_name(cls, resource_name: str):
FILL_FUNC_BODY @... | @attr.define(init=True, frozen=True)
class StudyResource:
"""Resource for Studies."""
owner_id: str = attr.ib(init=True, validator=_resource_component_validator)
study_id: str = attr.ib(init=True, validator=_resource_component_validator)
@classmethod
def from_name(cls, resource_name: str):
"""Creates St... | study_match = re.match(
r'^owners\/(?P<owner_id>[^\/]+)\/studies\/(?P<study_id>[^\/]+)$',
resource_name,
)
if study_match:
return StudyResource(
study_match.group('owner_id'), study_match.group('study_id')
)
else:
raise ValueError(
f'{repr(resource_... | """Creates StudyResource from a name."""
study_match = re.match(
r'^owners\/(?P<owner_id>[^\/]+)\/studies\/(?P<study_id>[^\/]+)$',
resource_name,
)
if study_match:
return StudyResource(
study_match.group('owner_id'), study_match.group('study_id')
)
else:
... | 27 | 304 | 151 | 455 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,114 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/resources.py | 223,225 | 198,239 | from_name | SuggestionOperationResource | 226,239 | 225,239 | @attr.define(init=True, frozen=True)
class SuggestionOperationResource:
"""Resource for Suggestion Operations."""
owner_id: str = attr.ib(init=True, validator=_resource_component_validator)
study_id: str = attr.ib(init=True, validator=_resource_component_validator)
client_id: str = attr.ib(init=True, validator... | @attr.define(init=True, frozen=True)
class SuggestionOperationResource:
"""Resource for Suggestion Operations."""
owner_id: str = attr.ib(init=True, validator=_resource_component_validator)
study_id: str = attr.ib(init=True, validator=_resource_component_validator)
client_id: str = attr.ib(init=True, validator... | operation_match = re.match(
r'^owners\/(?P<owner_id>[^\/]+)/operations/suggestion/(?P<study_id>[^\/]+)/(?P<client_id>[^\/]+)/(?P<operation_number>[^\/]+)$',
resource_name,
)
if operation_match:
return SuggestionOperationResource(
operation_match.group('owner_id'),
o... | """Creates SuggestionOperationResource from a name."""
operation_match = re.match(
r'^owners\/(?P<owner_id>[^\/]+)/operations/suggestion/(?P<study_id>[^\/]+)/(?P<client_id>[^\/]+)/(?P<operation_number>[^\/]+)$',
resource_name,
)
if operation_match:
return SuggestionOperationResourc... | 22 | 307 | 198 | 505 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,115 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/resources.py | 115,117 | 101,153 | from_name | TrialResource | 118,134 | 117,134 | @attr.define(init=True, frozen=True)
class TrialResource:
"""Resource for Trials."""
owner_id: str = attr.ib(init=True, validator=_resource_component_validator)
study_id: str = attr.ib(init=True, validator=_resource_component_validator)
trial_id: int = attr.ib(
init=True,
validator=[
attr... | @attr.define(init=True, frozen=True)
class TrialResource:
"""Resource for Trials."""
owner_id: str = attr.ib(init=True, validator=_resource_component_validator)
study_id: str = attr.ib(init=True, validator=_resource_component_validator)
trial_id: int = attr.ib(
init=True,
validator=[
attr... | trial_match = re.match(
r'^owners\/(?P<owner_id>[^\/]+)\/studies\/(?P<study_id>[^\/]+)\/trials\/(?P<trial_id>[^\/]+)$',
resource_name,
)
if trial_match:
return TrialResource(
trial_match.group('owner_id'),
trial_match.group('study_id'),
int(trial_match.gr... | """Creates TrialResource from a name."""
trial_match = re.match(
r'^owners\/(?P<owner_id>[^\/]+)\/studies\/(?P<study_id>[^\/]+)\/trials\/(?P<trial_id>[^\/]+)$',
resource_name,
)
if trial_match:
return TrialResource(
trial_match.group('owner_id'),
trial_match.gr... | 28 | 370 | 193 | 563 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,116 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/sql_datastore_test.py | 90,92 | 81,107 | test_local_hdd_persistence | SQLDataStoreAdditionalTest | 92,107 | 92,107 | class SQLDataStoreAdditionalTest(absltest.TestCase):
"""For additional tests outside of regular database functionality."""
def setUp(self):
super().setUp()
self.owner_id = 'my_username'
self.study_id = '123123123'
self.example_study = test_util.generate_study(self.owner_id, self.study_id)
@abslt... | class SQLDataStoreAdditionalTest(absltest.TestCase):
"""For additional tests outside of regular database functionality."""
def setUp(self):
super().setUp()
self.owner_id = 'my_username'
self.study_id = '123123123'
self.example_study = test_util.generate_study(self.owner_id, self.study_id)
@abslt... | db_path = os.path.join(absltest.get_default_test_tmpdir(), 'local.db')
sql_url = f'sqlite:///{db_path}'
engine = sqla.create_engine(sql_url, echo=True)
datastore = sql_datastore.SQLDataStore(engine)
datastore.create_study(self.example_study)
del datastore
engine2 = sqla.create_engine(sql_u... | db_path = os.path.join(absltest.get_default_test_tmpdir(), 'local.db')
sql_url = f'sqlite:///{db_path}'
engine = sqla.create_engine(sql_url, echo=True)
datastore = sql_datastore.SQLDataStore(engine)
datastore.create_study(self.example_study)
del datastore
engine2 = sqla.create_engine(sql_u... | 29 | 152 | 205 | 357 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,117 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/sql_datastore_test.py | 30,31 | 28,81 | setUp | SQLDataStoreTest | 31,53 | 31,53 | class SQLDataStoreTest(datastore_test_lib.DataStoreTestCase):
def setUp(self):
FILL_FUNC_BODY def test_study_api(self):
self.assertStudyAPI(self.datastore, self.example_study)
def test_trial(self):
self.assertTrialAPI(self.datastore, self.example_study, self.example_trials)
def test_suggestion_operati... | class SQLDataStoreTest(datastore_test_lib.DataStoreTestCase):
def setUp(self):
FILL_FUNC_BODY def test_study_api(self):
self.assertStudyAPI(self.datastore, self.example_study)
def test_trial(self):
self.assertTrialAPI(self.datastore, self.example_study, self.example_trials)
def test_suggestion_operati... | self.owner_id = 'my_username'
self.study_id = '123123123'
self.client_id = 'client_0'
self.example_study = test_util.generate_study(self.owner_id, self.study_id)
self.example_trials = test_util.generate_trials(
[1, 2], owner_id=self.owner_id, study_id=self.study_id
)
self.example_sug... | self.owner_id = 'my_username'
self.study_id = '123123123'
self.client_id = 'client_0'
self.example_study = test_util.generate_study(self.owner_id, self.study_id)
self.example_trials = test_util.generate_trials(
[1, 2], owner_id=self.owner_id, study_id=self.study_id
)
self.example_sug... | 52 | 291 | 324 | 615 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,118 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/_src/service/stubs_util_test.py | 27,32 | 25,38 | test_bad_endpoint | StubsUtilTest | 32,38 | 32,38 | class StubsUtilTest(parameterized.TestCase):
@parameterized.parameters(
(stubs_util.create_pythia_server_stub,),
(stubs_util.create_vizier_server_stub,),
)
def test_bad_endpoint(self, stub_creator):
FILL_FUNC_BODY | class StubsUtilTest(parameterized.TestCase):
@parameterized.parameters(
(stubs_util.create_pythia_server_stub,),
(stubs_util.create_vizier_server_stub,),
)
def test_bad_endpoint(self, stub_creator):
FILL_FUNC_BODY | # Make sure connection errors out instead of stalling forever.
endpoint = 'i_dont_exist'
with self.assertRaises(grpc.FutureTimeoutError):
stub_creator(endpoint, timeout=0.1)
| # Make sure connection errors out instead of stalling forever.
endpoint = 'i_dont_exist'
with self.assertRaises(grpc.FutureTimeoutError):
stub_creator(endpoint, timeout=0.1)
| 17 | 91 | 66 | 157 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,119 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/client/client_abc.py | 314,315 | 191,319 | materialize_state | StudyInterface | 316,319 | 315,319 | class StudyInterface(abc.ABC):
"""Responsible for study-level operations."""
@property
@abc.abstractmethod
def resource_name(self) -> str:
"""Globally unique identifier of the study in Vizier service."""
@abc.abstractmethod
def suggest(
self, *, count: Optional[int] = None, client_id: str = 'def... | class StudyInterface(abc.ABC):
"""Responsible for study-level operations."""
@property
@abc.abstractmethod
def resource_name(self) -> str:
"""Globally unique identifier of the study in Vizier service."""
@abc.abstractmethod
def suggest(
self, *, count: Optional[int] = None, client_id: str = 'def... | raise NotImplementedError(
f'materialize_state is not implemented in {type(self)}!'
)
| """#Materializes the study state."""
raise NotImplementedError(
f'materialize_state is not implemented in {type(self)}!'
)
| 9 | 1,094 | 33 | 1,127 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,121 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/interfaces/serializable.py | 112,114 | 87,127 | recover | Serializable | 122,124 | 114,124 | class Serializable(abc.ABC):
"""Objects that can be fully serialized.
Compared to PartiallySerializable, Serializable.recover() is a _classmethod_
not a regular method. The object's `State` in its entirety can be serialized
and then recovered.
NOTE: `State` here refers to the behavioral state that can be ve... | class Serializable(abc.ABC):
"""Objects that can be fully serialized.
Compared to PartiallySerializable, Serializable.recover() is a _classmethod_
not a regular method. The object's `State` in its entirety can be serialized
and then recovered.
NOTE: `State` here refers to the behavioral state that can be ve... | raise NotImplementedError('')
| """Creates a new Serializable object from metadata.
Args:
metadata:
Raises:
DecodeError: Object could not be recovered from the metadata.
"""
raise NotImplementedError('')
| 2 | 339 | 13 | 352 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,122 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/jax/optimizers.py | 33,35 | 1,38 | default_optimizer | 36,38 | 35,38 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # NOTE: Production algorithms are recommended to stay away from using this.
return JaxoptScipyLbfgsB(LbfgsBOptions(maxiter=maxiter, best_n=None))
| """Default optimizer and random restarts that work okay for most cases."""
# NOTE: Production algorithms are recommended to stay away from using this.
return JaxoptScipyLbfgsB(LbfgsBOptions(maxiter=maxiter, best_n=None))
| 15 | 437 | 52 | 489 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
47,125 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core.py | 858,861 | 788,898 | to_metrics | DefaultModelOutputConverter | 869,887 | 861,887 | class DefaultModelOutputConverter(ModelOutputConverter):
"""Converts measurements into numpy arrays."""
def __init__(
self,
metric_information: pyvizier.MetricInformation,
*,
flip_sign_for_minimization_metrics: bool = False,
shift_safe_metrics: bool = True,
dtype: Union[
... | class DefaultModelOutputConverter(ModelOutputConverter):
"""Converts measurements into numpy arrays."""
def __init__(
self,
metric_information: pyvizier.MetricInformation,
*,
flip_sign_for_minimization_metrics: bool = False,
shift_safe_metrics: bool = True,
dtype: Union[
... | if labels.ndim == 1:
labels = labels[:, None]
if labels.shape[1] > 1 or len(labels.shape) > 2:
raise ValueError('The input array must be of shape (num,) or (num, 1).')
labels = labels.flatten()
if (
self.shift_safe_metrics
and self._original_metric_information.type.is_safety... | """Converts an array of labels to pyvizier Metrics.
Args:
labels: (len(metrics),) or (len(metrics), 1) shaped array of labels.
Returns:
metrics: a list of pyvizier metrics.
"""
if labels.ndim == 1:
labels = labels[:, None]
if labels.shape[1] > 1 or len(labels.shape) > 2:
... | 64 | 1,047 | 211 | 1,258 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,127 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core.py | 271,272 | 218,297 | dict_like | DictOf2DArrays | 287,297 | 272,297 | class DictOf2DArrays(Mapping[str, np.ndarray]):
"""Dictionary of string to 2D arrays.
All arrays share the first dimension, which is at a high level, the number of
objects that this dictionary corresponds to.
Attributes:
size: Array's shape[0].
"""
def __init__(self, d: Mapping[str, np.ndarray]):
... | class DictOf2DArrays(Mapping[str, np.ndarray]):
"""Dictionary of string to 2D arrays.
All arrays share the first dimension, which is at a high level, the number of
objects that this dictionary corresponds to.
Attributes:
size: Array's shape[0].
"""
def __init__(self, d: Mapping[str, np.ndarray]):
... | begin = 0
new_dict = dict()
for k, v in self.items():
end = begin + v.shape[1]
new_dict[k] = array[:, begin:end].astype(v.dtype)
begin = end
return DictOf2DArrays(new_dict)
| """[Experimental] Converts an array into a dict with the same keys as this.
This function acts like an inverse of `asarray()`, i.e. it satisfies
`self.dict_like(self.asarray()) == self`.
Example:
d = DictOf2DArrays({'p1': [[1], [2], [3]], 'p2': [[4], [5], [6]]})
d.dict_like([[1, 2], [3, ... | 25 | 762 | 93 | 855 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,128 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core.py | 424,426 | 412,517 | scaler_from_spec | ModelInputArrayBijector | 427,484 | 426,484 | @dataclasses.dataclass
class ModelInputArrayBijector:
"""Transformations on the numpy arrays generated by ModelInputConverter."""
forward_fn: Callable[[np.ndarray], np.ndarray]
backward_fn: Callable[[np.ndarray], np.ndarray]
output_spec: NumpyArraySpec # Spec after forward_fn is applied.
@classmethod
def... | @dataclasses.dataclass
class ModelInputArrayBijector:
"""Transformations on the numpy arrays generated by ModelInputConverter."""
forward_fn: Callable[[np.ndarray], np.ndarray]
backward_fn: Callable[[np.ndarray], np.ndarray]
output_spec: NumpyArraySpec # Spec after forward_fn is applied.
@classmethod
def... | low, high = spec.bounds
if spec.type != NumpyArraySpecType.CONTINUOUS:
return cls.identity(attr.evolve(spec, scale=None))
if low == high:
def backward_fn(y):
return np.where(np.isfinite(y), y + low - 0.5, y)
def forward_fn(y):
return np.where(np.isfinite(y), y - low + 0.5... | """For continuous specs, linearize and scale it to (0, 1) range."""
low, high = spec.bounds
if spec.type != NumpyArraySpecType.CONTINUOUS:
return cls.identity(attr.evolve(spec, scale=None))
if low == high:
def backward_fn(y):
return np.where(np.isfinite(y), y + low - 0.5, y)
... | 262 | 623 | 835 | 1,458 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,129 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core.py | 783,785 | 740,788 | output_shape | ModelOutputConverter | 785,788 | 785,788 | class ModelOutputConverter(metaclass=abc.ABCMeta):
"""Metric converter interface.
Unlike ModelInputConverter, this class is currently designed to always
output a single-dimensional metric. This is because in standard Keras
workflows, output shapes must be known when defining a model. (In contrast,
input shap... | class ModelOutputConverter(metaclass=abc.ABCMeta):
"""Metric converter interface.
Unlike ModelInputConverter, this class is currently designed to always
output a single-dimensional metric. This is because in standard Keras
workflows, output shapes must be known when defining a model. (In contrast,
input shap... | return (None, 1)
| return (None, 1)
| 3 | 464 | 14 | 478 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,130 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core.py | 145,157 | 83,213 | from_parameter_config | NumpyArraySpec | 172,213 | 157,213 | @attr.define(frozen=True, auto_attribs=True, eq=True, hash=True)
class NumpyArraySpec:
"""Encodes what a feature array represents.
This class can be seen as a counterpart of Vizier ParameterConfig.
Vizier ParameterConfigs describe Trial parameters. NumpyArraySpec describes
numpy arrays returned from trial-to-n... | @attr.define(frozen=True, auto_attribs=True, eq=True, hash=True)
class NumpyArraySpec:
"""Encodes what a feature array represents.
This class can be seen as a counterpart of Vizier ParameterConfig.
Vizier ParameterConfigs describe Trial parameters. NumpyArraySpec describes
numpy arrays returned from trial-to-n... | the_type = type_factory(pc)
if the_type == NumpyArraySpecType.CONTINUOUS:
return NumpyArraySpec(
the_type,
np.dtype(floating_dtype),
bounds=pc.bounds,
num_dimensions=1,
scale=pc.scale_type,
name=pc.name,
num_oovs=0,
)
elif the... | """Factory function.
Args:
pc:
type_factory: NumpyArraySpecType has `default_factory` and
`embedding_factory`. The difference is in how they handle non-continuous
parameters.
floating_dtype: Dtype of the floating outputs.
int_dtype: Dtype of the integer outputs.
pa... | 73 | 1,158 | 464 | 1,622 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,131 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core.py | 50,54 | 36,83 | default_factory | NumpyArraySpecType | 55,67 | 54,67 | class NumpyArraySpecType(enum.Enum):
"""Type information for NumpyArraySpec.
CONTINUOUS: Continuous parameter
DISCRETE: Discrete/integer/categorical parameter
ONEHOT_EMBEDDING: One-hot embedding of DISCRETE.
OBJECT: Object type that can hold any value.
"""
CONTINUOUS = 'CONTINUOUS'
DISCRETE = 'DISCRET... | class NumpyArraySpecType(enum.Enum):
"""Type information for NumpyArraySpec.
CONTINUOUS: Continuous parameter
DISCRETE: Discrete/integer/categorical parameter
ONEHOT_EMBEDDING: One-hot embedding of DISCRETE.
OBJECT: Object type that can hold any value.
"""
CONTINUOUS = 'CONTINUOUS'
DISCRETE = 'DISCRET... | if pc.type == pyvizier.ParameterType.DOUBLE:
return NumpyArraySpecType.CONTINUOUS
elif pc.type in (
pyvizier.ParameterType.DISCRETE,
pyvizier.ParameterType.CATEGORICAL,
pyvizier.ParameterType.INTEGER,
):
return NumpyArraySpecType.DISCRETE
elif pc.type == pyvizier.Para... | """SpecType when encoding discretes as integer indices."""
if pc.type == pyvizier.ParameterType.DOUBLE:
return NumpyArraySpecType.CONTINUOUS
elif pc.type in (
pyvizier.ParameterType.DISCRETE,
pyvizier.ParameterType.CATEGORICAL,
pyvizier.ParameterType.INTEGER,
):
retur... | 26 | 395 | 163 | 558 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,132 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core.py | 1238,1239 | 1216,1324 | to_labels | TrialToArrayConverter | 1240,1243 | 1239,1243 | @attr.define
class TrialToArrayConverter:
"""EXPERIMENTAL: A quick-and-easy converter that returns a single array.
Unlike TrialtoNumpyDict converters, `to_features` and `to_labels`
return a single array of floating numbers. CATEGORICAL and DISCRETE parameters
are one-hot embedded.
IMPORTANT: Use a factory m... | @attr.define
class TrialToArrayConverter:
"""EXPERIMENTAL: A quick-and-easy converter that returns a single array.
Unlike TrialtoNumpyDict converters, `to_features` and `to_labels`
return a single array of floating numbers. CATEGORICAL and DISCRETE parameters
are one-hot embedded.
IMPORTANT: Use a factory m... | # Pad up the labels.
return dict_to_array(self._impl.to_labels(trials))
| """Returns the labels array with dimension: (n_trials, n_metrics)."""
# Pad up the labels.
return dict_to_array(self._impl.to_labels(trials))
| 7 | 1,170 | 32 | 1,202 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,136 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core_test.py | 240,241 | 217,248 | test_bad_addition | DictOf2DArraysTest | 241,248 | 241,248 | class DictOf2DArraysTest(absltest.TestCase):
def test_bad_shapes(self):
with self.assertRaises(ValueError):
core.DictOf2DArrays({'a': rnd([10, 2]), 'b': rnd([5, 2])})
def test_bad_dim(self):
with self.assertRaises(ValueError):
core.DictOf2DArrays({'a': rnd([10, 2, 1])})
def test_size(self):... | class DictOf2DArraysTest(absltest.TestCase):
def test_bad_shapes(self):
with self.assertRaises(ValueError):
core.DictOf2DArrays({'a': rnd([10, 2]), 'b': rnd([5, 2])})
def test_bad_dim(self):
with self.assertRaises(ValueError):
core.DictOf2DArrays({'a': rnd([10, 2, 1])})
def test_size(self):... | # Shape of b doesn't match.
d1 = core.DictOf2DArrays({'a': rnd([10, 2]), 'b': rnd([10, 1])})
d2 = core.DictOf2DArrays({'a': rnd([5, 2]), 'b': rnd([5, 3])})
with self.assertRaises(ValueError):
_ = d1 + d2
| # Shape of b doesn't match.
d1 = core.DictOf2DArrays({'a': rnd([10, 2]), 'b': rnd([10, 1])})
d2 = core.DictOf2DArrays({'a': rnd([5, 2]), 'b': rnd([5, 3])})
with self.assertRaises(ValueError):
_ = d1 + d2
| 29 | 386 | 122 | 508 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,137 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core_test.py | 179,180 | 177,214 | test_2d | DictToArrayTest | 180,187 | 180,187 | class DictToArrayTest(absltest.TestCase):
def test_2d(self):
FILL_FUNC_BODY def test_4d(self):
self.assertSequenceEqual(
core.dict_to_array({
1: np.random.random((2, 1, 10, 2)),
2: np.random.random((2, 1, 10, 1)),
}).shape,
(2, 1, 10, 3),
)
def test_dict_li... | class DictToArrayTest(absltest.TestCase):
def test_2d(self):
FILL_FUNC_BODY def test_4d(self):
self.assertSequenceEqual(
core.dict_to_array({
1: np.random.random((2, 1, 10, 2)),
2: np.random.random((2, 1, 10, 1)),
}).shape,
(2, 1, 10, 3),
)
def test_dict_li... | self.assertSequenceEqual(
core.dict_to_array(
{1: np.random.random((10, 2)), 2: np.random.random((10, 1))}
).shape,
(10, 3),
)
| self.assertSequenceEqual(
core.dict_to_array(
{1: np.random.random((10, 2)), 2: np.random.random((10, 1))}
).shape,
(10, 3),
)
| 12 | 435 | 76 | 511 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,138 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core_test.py | 1336,1337 | 1292,1361 | testScalarFromSinglePointSpec | ModelInputArrayBijectorTest | 1337,1361 | 1337,1361 | class ModelInputArrayBijectorTest(absltest.TestCase):
def testIdentityBijector(self):
parameter_config = pyvizier.ParameterConfig.factory('p', bounds=(0.0, 1.0))
spec = core.NumpyArraySpec(
name='p',
type=core.NumpyArraySpecType.default_factory(parameter_config),
dtype=np.dtype(np.flo... | class ModelInputArrayBijectorTest(absltest.TestCase):
def testIdentityBijector(self):
parameter_config = pyvizier.ParameterConfig.factory('p', bounds=(0.0, 1.0))
spec = core.NumpyArraySpec(
name='p',
type=core.NumpyArraySpecType.default_factory(parameter_config),
dtype=np.dtype(np.flo... | parameter_config = pyvizier.ParameterConfig.factory('p', bounds=(1.0, 1.0))
spec = core.NumpyArraySpec(
name='p',
type=core.NumpyArraySpecType.default_factory(parameter_config),
dtype=np.dtype(np.float32),
bounds=(1.0, 1.0),
num_dimensions=1,
num_oovs=0,
)
... | parameter_config = pyvizier.ParameterConfig.factory('p', bounds=(1.0, 1.0))
spec = core.NumpyArraySpec(
name='p',
type=core.NumpyArraySpecType.default_factory(parameter_config),
dtype=np.dtype(np.float32),
bounds=(1.0, 1.0),
num_dimensions=1,
num_oovs=0,
)
... | 38 | 639 | 367 | 1,006 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,139 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core_test.py | 36,37 | 34,50 | test_automl_study | TrialToArrayConverterConditionalSpaceTest | 37,50 | 37,50 | class TrialToArrayConverterConditionalSpaceTest(parameterized.TestCase):
def test_automl_study(self):
FILL_FUNC_BODY | class TrialToArrayConverterConditionalSpaceTest(parameterized.TestCase):
def test_automl_study(self):
FILL_FUNC_BODY | space = test_studies.conditional_automl_space()
converter = core.TrialToArrayConverter.from_study_config(
pyvizier.ProblemStatement(search_space=space)
)
features = converter.to_features([pyvizier.Trial()])
np.testing.assert_equal(
features,
np.array(
[[0.0, 0.0, ... | space = test_studies.conditional_automl_space()
converter = core.TrialToArrayConverter.from_study_config(
pyvizier.ProblemStatement(search_space=space)
)
features = converter.to_features([pyvizier.Trial()])
np.testing.assert_equal(
features,
np.array(
[[0.0, 0.0, ... | 27 | 41 | 171 | 212 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,140 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/core_test.py | 53,54 | 50,177 | setUp | TrialToArrayConverterTest | 54,72 | 54,72 | class TrialToArrayConverterTest(parameterized.TestCase):
"""Test TrialToArrayConverter class."""
def setUp(self):
FILL_FUNC_BODY def test_back_to_back_conversion(self):
converter = core.TrialToArrayConverter.from_study_config(self._study_config)
self.assertSequenceEqual(
[t.parameters for t in sel... | class TrialToArrayConverterTest(parameterized.TestCase):
"""Test TrialToArrayConverter class."""
def setUp(self):
FILL_FUNC_BODY def test_back_to_back_conversion(self):
converter = core.TrialToArrayConverter.from_study_config(self._study_config)
self.assertSequenceEqual(
[t.parameters for t in sel... | super().setUp()
self._study_config = pyvizier.ProblemStatement(
search_space=test_studies.flat_space_with_all_types(),
metric_information=[
pyvizier.MetricInformation(
'x1', goal=pyvizier.ObjectiveMetricGoal.MAXIMIZE
)
],
)
self._designer ... | super().setUp()
self._study_config = pyvizier.ProblemStatement(
search_space=test_studies.flat_space_with_all_types(),
metric_information=[
pyvizier.MetricInformation(
'x1', goal=pyvizier.ObjectiveMetricGoal.MAXIMIZE
)
],
)
self._designer ... | 29 | 1,423 | 206 | 1,629 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,141 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/embedder.py | 114,115 | 44,157 | map | ProblemAndTrialsScaler | 116,134 | 115,134 | class ProblemAndTrialsScaler:
"""Vizier problem statement and trials scaler."""
def __init__(self, problem: vz.ProblemStatement):
"""Initializes the class by creating a converter and scaled problem statement.
Arguments:
problem: The ProblemStatemet to be scaled.
"""
def create_param_convert... | class ProblemAndTrialsScaler:
"""Vizier problem statement and trials scaler."""
def __init__(self, problem: vz.ProblemStatement):
"""Initializes the class by creating a converter and scaled problem statement.
Arguments:
problem: The ProblemStatemet to be scaled.
"""
def create_param_convert... | embedded_trials = []
for trial in trials:
parameters = vz.ParameterDict()
for name, feature in self._converter.to_features([trial]).items():
if (
self.problem_statement.search_space.get(name).type
== vz.ParameterType.CATEGORICAL
):
# CATEGORICAL para... | """Map trials from the original search space to the embedded space."""
embedded_trials = []
for trial in trials:
parameters = vz.ParameterDict()
for name, feature in self._converter.to_features([trial]).items():
if (
self.problem_statement.search_space.get(name).type
... | 54 | 1,195 | 204 | 1,399 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,143 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/input_warping.py | 58,59 | 1,101 | kumaraswamy_inv_cdf | 69,72 | 59,72 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | return (1 - (1 - f) ** (1 / b)) ** (1 / a)
| """Compute the inverse of the Kumaraswamy CDF.
Arguments:
f: values in [0,1]. shape: (num_samples, num_cdfs)
a: positive value.
b: positive value.
Returns:
The Inv_CDF(x). shape: (num_samples, num_features).
"""
return (1 - (1 - f) ** (1 / b)) ** (1 / a)
| 14 | 1,049 | 28 | 1,077 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
47,144 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/input_warping.py | 93,94 | 72,101 | to_xy | KumaraswamyInputWarpingConverter | 94,96 | 94,96 | @attr.define
class KumaraswamyInputWarpingConverter:
"""Input Warping based on Kumaraswamy distribution.
Reference: https://en.wikipedia.org/wiki/Kumaraswamy_distribution
"""
converter: core.TrialToArrayConverter
a: float = attr.field(validator=attr.validators.instance_of(float))
b: float = attr.field(val... | @attr.define
class KumaraswamyInputWarpingConverter:
"""Input Warping based on Kumaraswamy distribution.
Reference: https://en.wikipedia.org/wiki/Kumaraswamy_distribution
"""
converter: core.TrialToArrayConverter
a: float = attr.field(validator=attr.validators.instance_of(float))
b: float = attr.field(val... | return self.to_features(trials), self.converter.to_labels(trials)
| return self.to_features(trials), self.converter.to_labels(trials)
| 3 | 373 | 27 | 400 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,145 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/input_warping_test.py | 42,43 | 27,69 | test_convert_trials | InputWarpingTest | 43,69 | 43,69 | class InputWarpingTest(absltest.TestCase):
def test_kumaraswamy_transformation(self):
rng = np.random.default_rng(seed=0)
for a in np.linspace(0.01, 2.0, 50):
for b in np.linspace(0.01, 2.0, 50):
x = rng.uniform(size=(50, 20))
f = input_warping.kumaraswamy_cdf(x, a, b)
# Test th... | class InputWarpingTest(absltest.TestCase):
def test_kumaraswamy_transformation(self):
rng = np.random.default_rng(seed=0)
for a in np.linspace(0.01, 2.0, 50):
for b in np.linspace(0.01, 2.0, 50):
x = rng.uniform(size=(50, 20))
f = input_warping.kumaraswamy_cdf(x, a, b)
# Test th... | rng = np.random.default_rng(seed=0)
search_space = vz.SearchSpace()
for i in range(16):
search_space.root.add_float_param(f"x{i}", 0.0, 1.0)
problem = vz.ProblemStatement(search_space)
converter = converters.TrialToArrayConverter.from_study_config(problem)
input_warper = input_warping.Kuma... | rng = np.random.default_rng(seed=0)
search_space = vz.SearchSpace()
for i in range(16):
search_space.root.add_float_param(f"x{i}", 0.0, 1.0)
problem = vz.ProblemStatement(search_space)
converter = converters.TrialToArrayConverter.from_study_config(problem)
input_warper = input_warping.Kuma... | 84 | 269 | 424 | 693 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,146 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/jnp_converters_test.py | 37,38 | 35,92 | test_padding | PaddedTrialToArrayConverterTest | 39,92 | 38,92 | class PaddedTrialToArrayConverterTest(parameterized.TestCase):
def test_padding(self):
FILL_FUNC_BODY | class PaddedTrialToArrayConverterTest(parameterized.TestCase):
def test_padding(self):
"""Tests various padding schedules."""
FILL_FUNC_BODY |
padding_schedule = padding.PaddingSchedule(
num_trials=padding.PaddingType.POWERS_OF_2,
num_features=padding.PaddingType.MULTIPLES_OF_10,
num_metrics=padding.PaddingType.NONE,
)
problem = vz.ProblemStatement(test_studies.flat_space_with_all_types())
problem.metric_information.ap... | """Tests various padding schedules."""
padding_schedule = padding.PaddingSchedule(
num_trials=padding.PaddingType.POWERS_OF_2,
num_features=padding.PaddingType.MULTIPLES_OF_10,
num_metrics=padding.PaddingType.NONE,
)
problem = vz.ProblemStatement(test_studies.flat_space_with_all... | 69 | 45 | 591 | 636 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,147 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/jnp_converters_test.py | 159,160 | 92,199 | test_multi_metrics | TrialToContinuousAndCategoricalConverterTest | 160,199 | 160,199 | class TrialToContinuousAndCategoricalConverterTest(parameterized.TestCase):
"""Test TrialToContinuousAndCategoricalConverter class."""
def setUp(self):
super().setUp()
self._study_config = vz.ProblemStatement(
search_space=test_studies.flat_space_with_all_types(),
metric_information=[
... | class TrialToContinuousAndCategoricalConverterTest(parameterized.TestCase):
"""Test TrialToContinuousAndCategoricalConverter class."""
def setUp(self):
super().setUp()
self._study_config = vz.ProblemStatement(
search_space=test_studies.flat_space_with_all_types(),
metric_information=[
... | search_space = vz.SearchSpace()
search_space.root.add_float_param('x', 0.0, 1.0)
problem = vz.ProblemStatement(
search_space=search_space,
metric_information=vz.MetricsConfig(
metrics=[
vz.MetricInformation(
'obj1', goal=vz.ObjectiveMetricGoal.... | search_space = vz.SearchSpace()
search_space.root.add_float_param('x', 0.0, 1.0)
problem = vz.ProblemStatement(
search_space=search_space,
metric_information=vz.MetricsConfig(
metrics=[
vz.MetricInformation(
'obj1', goal=vz.ObjectiveMetricGoal.... | 87 | 886 | 539 | 1,425 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,148 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/padding.py | 34,37 | 1,98 | _padded_dimensions | 38,54 | 37,54 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | new_dims = []
for dim, padding_type in zip(dims, padding_types):
if padding_type == PaddingType.NONE:
new_dims.append(dim)
elif padding_type == PaddingType.MULTIPLES_OF_10:
new_dims.append(int(math.ceil(dim / 10.0)) * 10)
elif padding_type == PaddingType.POWERS_OF_2:
if dim == 0:
... | """Returns the padded shape according to `padding_types`."""
new_dims = []
for dim, padding_type in zip(dims, padding_types):
if padding_type == PaddingType.NONE:
new_dims.append(dim)
elif padding_type == PaddingType.MULTIPLES_OF_10:
new_dims.append(int(math.ceil(dim / 10.0)) * 10)
elif pa... | 43 | 820 | 217 | 1,037 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
47,149 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/padding.py | 84,85 | 54,98 | pad_features | PaddingSchedule | 86,90 | 85,90 | @attrs.define(frozen=True, kw_only=True, hash=True, eq=True)
class PaddingSchedule:
"""Convenience class for creating `PaddedArray`."""
_num_trials: PaddingType = PaddingType.NONE
_num_features: PaddingType = PaddingType.NONE
_num_metrics: PaddingType = PaddingType.NONE
_int_default: int = -1
_float_defau... | @attrs.define(frozen=True, kw_only=True, hash=True, eq=True)
class PaddingSchedule:
"""Convenience class for creating `PaddedArray`."""
_num_trials: PaddingType = PaddingType.NONE
_num_features: PaddingType = PaddingType.NONE
_num_metrics: PaddingType = PaddingType.NONE
_int_default: int = -1
_float_defau... | return self._pad_trailing_dims(
features, [self._num_trials, self._num_features]
)
| """Pads features in to a `PaddedArray`."""
return self._pad_trailing_dims(
features, [self._num_trials, self._num_features]
)
| 6 | 467 | 39 | 506 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,150 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/padding_test.py | 28,29 | 26,64 | test_padding | PaddingTest | 29,47 | 29,47 | class PaddingTest(parameterized.TestCase):
def test_padding(self):
FILL_FUNC_BODY def test_nopadding(self):
features = np.random.randn(13, 7)
labels = np.random.randn(13, 3)
schedule = padding.PaddingSchedule(
num_trials=padding.PaddingType.NONE,
num_features=padding.PaddingType.NONE,
... | class PaddingTest(parameterized.TestCase):
def test_padding(self):
FILL_FUNC_BODY def test_nopadding(self):
features = np.random.randn(13, 7)
labels = np.random.randn(13, 3)
schedule = padding.PaddingSchedule(
num_trials=padding.PaddingType.NONE,
num_features=padding.PaddingType.NONE,
... | features = np.random.randn(13, 7)
labels = np.random.randn(13, 3)
schedule = padding.PaddingSchedule(
num_trials=padding.PaddingType.MULTIPLES_OF_10,
num_features=padding.PaddingType.POWERS_OF_2,
num_metrics=padding.PaddingType.POWERS_OF_2,
)
padded = schedule.pad_features(... | features = np.random.randn(13, 7)
labels = np.random.randn(13, 3)
schedule = padding.PaddingSchedule(
num_trials=padding.PaddingType.MULTIPLES_OF_10,
num_features=padding.PaddingType.POWERS_OF_2,
num_metrics=padding.PaddingType.POWERS_OF_2,
)
padded = schedule.pad_features(... | 31 | 212 | 251 | 463 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,152 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/spatio_temporal.py | 283,284 | 229,336 | to_features | SparseSpatioTemporalConverter | 296,308 | 284,308 | class SparseSpatioTemporalConverter(core.TrialToNumpyDict):
"""Optimized for when the temporal dimensions are not well-aligned.
This converter inherits from the `TrialToNumpyDict` abstractions. Timestamp
becomes an extra feature dimension.
For inference, however, the user has to provide `temporal_index_points... | class SparseSpatioTemporalConverter(core.TrialToNumpyDict):
"""Optimized for when the temporal dimensions are not well-aligned.
This converter inherits from the `TrialToNumpyDict` abstractions. Timestamp
becomes an extra feature dimension.
For inference, however, the user has to provide `temporal_index_points... | features = self.trial_converter.to_features(
[trial]) # Dict values have shape [1,1]
# Repeat the features T_i times. Dict values have shape [T_i,1]
features = {
k: np.tile(v, (len(temporal_index_points), 1))
for k, v in features.items()
}
# Add the timestamp feature.
f... | """Converts a trial at the specified index points.
Args:
trial:
temporal_index_points:
Returns:
Each array has shape (B,_) where _ is determined by injected
ModelInputConverters and B = len(trials) * len(temporal_index_points).
In addition to what ModelInputConverters return,... | 44 | 1,156 | 150 | 1,306 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,154 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/spatio_temporal_test.py | 213,214 | 211,271 | test_all | DenseSpatioTemporalConverterTest | 214,238 | 214,238 | class DenseSpatioTemporalConverterTest(absltest.TestCase):
def test_all(self):
FILL_FUNC_BODY def test_xty(self):
extractor = st.TimedLabelsExtractor(
_metric_converters, 'steps', value_extraction='raw')
parameter = core.DefaultModelInputConverter(
pyvizier.ParameterConfig.factory(name='x1',... | class DenseSpatioTemporalConverterTest(absltest.TestCase):
def test_all(self):
FILL_FUNC_BODY def test_xty(self):
extractor = st.TimedLabelsExtractor(
_metric_converters, 'steps', value_extraction='raw')
parameter = core.DefaultModelInputConverter(
pyvizier.ParameterConfig.factory(name='x1',... | extractor = st.TimedLabelsExtractor(
_metric_converters, 'steps', value_extraction='raw')
converter = st.DenseSpatioTemporalConverter([],
extractor,
temporal_index_points=np.array(
... | extractor = st.TimedLabelsExtractor(
_metric_converters, 'steps', value_extraction='raw')
converter = st.DenseSpatioTemporalConverter([],
extractor,
temporal_index_points=np.array(
... | 58 | 392 | 321 | 713 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,155 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/spatio_temporal_test.py | 183,184 | 181,211 | test_all | SparseSpatioTemporalConverterTest | 184,211 | 184,211 | class SparseSpatioTemporalConverterTest(absltest.TestCase):
def test_all(self):
FILL_FUNC_BODY | class SparseSpatioTemporalConverterTest(absltest.TestCase):
def test_all(self):
FILL_FUNC_BODY | extractor = st.TimedLabelsExtractor(
_metric_converters, 'steps', value_extraction='raw')
converter = st.SparseSpatioTemporalConverter([], extractor)
features, labels = converter.to_xy(_trials)
np.testing.assert_equal(features, {
'steps':
np.array([[1.], [2.], [3.], [1.], [5... | extractor = st.TimedLabelsExtractor(
_metric_converters, 'steps', value_extraction='raw')
converter = st.SparseSpatioTemporalConverter([], extractor)
features, labels = converter.to_xy(_trials)
np.testing.assert_equal(features, {
'steps':
np.array([[1.], [2.], [3.], [1.], [5... | 65 | 39 | 384 | 423 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,156 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/pyvizier/converters/spatio_temporal_test.py | 114,115 | 79,181 | test_labels_raw | TimedLabelsExtractorTest | 115,125 | 115,125 | class TimedLabelsExtractorTest(absltest.TestCase):
def test_steps(self):
converter = st.TimedLabelsExtractor(
_metric_converters, 'steps', value_extraction='raw')
timed_labels = converter.convert(_trials)
np.testing.assert_almost_equal(
timed_labels[0].times,
np.asarray([1, 2, 3],... | class TimedLabelsExtractorTest(absltest.TestCase):
def test_steps(self):
converter = st.TimedLabelsExtractor(
_metric_converters, 'steps', value_extraction='raw')
timed_labels = converter.convert(_trials)
np.testing.assert_almost_equal(
timed_labels[0].times,
np.asarray([1, 2, 3],... | converter = st.TimedLabelsExtractor(
_metric_converters, 'elapsed_secs', value_extraction='raw')
timed_labels = converter.convert(_trials)
np.testing.assert_almost_equal(
timed_labels[0].labels['y1'],
np.asarray([1, 3, 2], dtype=np.float32)[:, np.newaxis])
np.testing.assert_almos... | converter = st.TimedLabelsExtractor(
_metric_converters, 'elapsed_secs', value_extraction='raw')
timed_labels = converter.convert(_trials)
np.testing.assert_almost_equal(
timed_labels[0].labels['y1'],
np.asarray([1, 3, 2], dtype=np.float32)[:, np.newaxis])
np.testing.assert_almos... | 23 | 1,437 | 177 | 1,614 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,157 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/utils/attrs_utils.py | 70,71 | 1,110 | shape_equals | 93,110 | 71,110 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
def validator(instance, attribute, value) -> None:
shape = instance_to_shape(instance)
def _validator_boolean():
if len(value.shape) != len(shape):
return False
for s1, s2 in zip(value.shape, shape):
if (s2 is not None) and (s1 != s2):
return False
return True
... | """Creates a shape validator for attrs.
For example, _shape_equals(lambda s : [3, None]) validates that the shape has
length 2 and its first element is 3.
Code Example:
@attrs.define
class TestAttr:
x = attrs.field(validator=attrs_utils.shape_equals(lambda v: (3, v.d)))
d = attrs.field()
_TestA... | 55 | 883 | 172 | 1,055 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
47,158 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/utils/attrs_utils_test.py | 97,98 | 92,106 | test_good_shape_none | ShapeEqualsTest | 98,101 | 98,101 | class ShapeEqualsTest(absltest.TestCase):
def test_good_shape(self):
_ShapeEqualsTestAttr(np.zeros([3, 2]), 2)
def test_good_shape_none(self):
FILL_FUNC_BODY def test_bad_shape(self):
with self.assertRaises(ValueError):
_ShapeEqualsTestAttr(np.zeros([3, 2]), 4)
| class ShapeEqualsTest(absltest.TestCase):
def test_good_shape(self):
_ShapeEqualsTestAttr(np.zeros([3, 2]), 2)
def test_good_shape_none(self):
FILL_FUNC_BODY def test_bad_shape(self):
with self.assertRaises(ValueError):
_ShapeEqualsTestAttr(np.zeros([3, 2]), 4)
| _ShapeEqualsTestAttr(np.zeros([3, 5]), None)
_ShapeEqualsTestAttr(np.zeros([3, 0]), None)
| _ShapeEqualsTestAttr(np.zeros([3, 5]), None)
_ShapeEqualsTestAttr(np.zeros([3, 0]), None)
| 6 | 118 | 46 | 164 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,159 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/utils/attrs_utils_test.py | 77,78 | 29,86 | test_good_shape_none | ValidatorsTest | 78,81 | 78,81 | class ValidatorsTest(parameterized.TestCase):
@parameterized.parameters(
(attrs_utils.assert_not_empty, [], False),
(attrs_utils.assert_not_empty, [1], True),
(attrs_utils.assert_not_negative, 0, -1),
(attrs_utils.assert_not_negative, 0, True),
(attrs_utils.assert_not_negative, 1, True)... | class ValidatorsTest(parameterized.TestCase):
@parameterized.parameters(
(attrs_utils.assert_not_empty, [], False),
(attrs_utils.assert_not_empty, [1], True),
(attrs_utils.assert_not_negative, 0, -1),
(attrs_utils.assert_not_negative, 0, True),
(attrs_utils.assert_not_negative, 1, True)... | _ShapeEqualsTestAttr(np.zeros([3, 5]), None)
_ShapeEqualsTestAttr(np.zeros([3, 0]), None)
| _ShapeEqualsTestAttr(np.zeros([3, 5]), None)
_ShapeEqualsTestAttr(np.zeros([3, 0]), None)
| 6 | 617 | 46 | 663 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,160 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/utils/json_utils.py | 47,48 | 1,77 | numpy_hook | 49,56 | 48,56 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | if 'dtype' not in obj:
return obj
if 'shape' not in obj:
return obj
return np.array(obj['value'], dtype=obj['dtype']).reshape(obj['shape'])
| """Example: json.loads(..., object_hook=numpy_hook)."""
if 'dtype' not in obj:
return obj
if 'shape' not in obj:
return obj
return np.array(obj['value'], dtype=obj['dtype']).reshape(obj['shape'])
| 17 | 713 | 65 | 778 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | |
47,161 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/utils/json_utils.py | 68,69 | 66,77 | default | MetadataEncoder | 69,77 | 69,77 | class MetadataEncoder(json.JSONEncoder):
def default(self, o: Any) -> Any:
FILL_FUNC_BODY | class MetadataEncoder(json.JSONEncoder):
def default(self, o: Any) -> Any:
FILL_FUNC_BODY | if isinstance(o, vz.Metadata):
d = dict(o)
d |= {ns.encode(): o.ns(ns) for ns in o.subnamespaces()}
return d
elif not isinstance(o, dict) and isinstance(o, Mapping):
# Handles FrozenDict and any dict-like structures.
return dict(o)
return o
| if isinstance(o, vz.Metadata):
d = dict(o)
d |= {ns.encode(): o.ns(ns) for ns in o.subnamespaces()}
return d
elif not isinstance(o, dict) and isinstance(o, Mapping):
# Handles FrozenDict and any dict-like structures.
return dict(o)
return o
| 34 | 39 | 105 | 144 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
47,162 | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier | /home/hieuvd/dung_repo/raw/stars_03/google_vizier/vizier/vizier/utils/json_utils.py | 30,31 | 27,47 | default | NumpyEncoder | 31,47 | 31,47 | class NumpyEncoder(json.JSONEncoder):
"""Example: json.dumps(np.array(...), cls=NumpyEncoder)."""
def default(self, o: Any) -> Any:
FILL_FUNC_BODY | class NumpyEncoder(json.JSONEncoder):
"""Example: json.dumps(np.array(...), cls=NumpyEncoder)."""
def default(self, o: Any) -> Any:
FILL_FUNC_BODY | if not isinstance(o, dict) and isinstance(o, Mapping):
# Handles FrozenDict and any dict-like structures.
return dict(o)
elif set(dir(o)).issuperset(set(['tolist', 'dtype', 'shape'])):
# Any numpy.array-like objects.
# Shape must be dumped and restored, in case that the array has shape
... | if not isinstance(o, dict) and isinstance(o, Mapping):
# Handles FrozenDict and any dict-like structures.
return dict(o)
elif set(dir(o)).issuperset(set(['tolist', 'dtype', 'shape'])):
# Any numpy.array-like objects.
# Shape must be dumped and restored, in case that the array has shape
... | 55 | 66 | 184 | 250 | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2024 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.