pygx.tuning¶
Distributed tuning with pluggable backends.
tuning
¶
Distributed tuning with pluggable backends.
pygx.iter provides an interface for sampling examples from a search
space within a process. To support distributed tuning, PyGX introduces
pygx.sample, which is almost identical but with more features:
- Allow multiple worker processes (aka. workers) to collaborate on a search with failover handling.
- Each worker can process different trials, or can cowork on the same trials via work groups.
- Provide APIs for communicating between the co-workers.
- Provide API for retrieving the search results.
- Provide a pluggable backend system for supporting user infrastructures.
Backend
¶
Backend(
name: str | None = None,
group: None | int | str = None,
dna_spec: DNASpec | None = None,
algorithm: DNAGenerator | None = None,
metrics_to_optimize: Sequence[str] | None = None,
early_stopping_policy: EarlyStoppingPolicy | None = None,
num_examples: int | None = None,
**kwargs: Any
)
Interface for the tuning backend.
Source code in pygx/tuning/_backend.py
create
classmethod
¶
create(
name: str | None,
group: None | int | str,
dna_spec: DNASpec,
algorithm: DNAGenerator,
metrics_to_optimize: Sequence[str],
early_stopping_policy: EarlyStoppingPolicy | None = None,
num_examples: int | None = None,
**kwargs: Any
) -> Backend
Create an instance of Backend based on pg.sample arguments.
The default implementation is to pass through all the arguments to
__init__ for creating an instance of the backend. Users can override.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
A string as a unique identifier for current sampling. Two separate
calls to |
required |
group
|
None | int | str
|
An string or integer as the group ID of current process in
distributed sampling, which will be used to group different workers into
co-worker groups. Workers with the same group id will work on the same
trial. On the contrary, workers in different groups will always be
working with different trials. If not specified, each worker in current
sampling will be in different groups. |
required |
dna_spec
|
DNASpec
|
An |
required |
algorithm
|
DNAGenerator
|
The search algorithm that samples the search space. |
required |
metrics_to_optimize
|
Sequence[str]
|
A sequence of string as the names of the metrics to be optimized by the algorithm, which is ['reward'] by default. When specified, it should have only 1 item for single-objective algorithm and can have multiple items for algorithms that support multi-objective optimization. |
required |
early_stopping_policy
|
EarlyStoppingPolicy | None
|
An optional early stopping policy for user to tell
if incremental evaluation (which reports multiple measurements) on each
example can be early short circuited.
After each call to |
None
|
num_examples
|
int | None
|
An optional integer as the max number of examples to sample. If None, sample will return an iterator of infinite examples. |
None
|
**kwargs
|
Any
|
Arguments passed to the |
{}
|
Returns:
| Type | Description |
|---|---|
Backend
|
A |
Source code in pygx/tuning/_backend.py
EarlyStoppingPolicy
¶
EarlyStoppingPolicy(
*,
allow_partial: bool = False,
sealed: bool | None = None,
root_path: KeyPath | None = None,
explicit_init: bool = False,
**kwargs: Any
)
Bases: Object
Interface for early stopping policy.
Source code in pygx/symbolic/_object.py
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 | |
setup
¶
setup(dna_spec: DNASpec) -> None
Setup states of an early stopping policy based on dna_spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dna_spec
|
DNASpec
|
DNASpec for DNA to propose. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
if dna_spec is not supported. |
Source code in pygx/tuning/_early_stopping.py
recover
¶
recover(history: Iterable[Trial]) -> None
Recover states by replaying the trial history.
Subclass can override.
NOTE: recover will always be called before the first should_stop_early
is called. It could be called multiple times if there are multiple source
of history, e.g: trials from a previous study and existing trials from
current study.
The default behavior is to replay should_stop_early on all trials that
contain all intermediate measurements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
history
|
Iterable[Trial]
|
An iterable object of trials. |
required |
Source code in pygx/tuning/_early_stopping.py
Feedback
¶
Interface for the feedback object for a trial.
Feedback object is an agent to communicate to the search algorithm and other workers based on current trial, which includes:
-
Information about current example:
-
id: The ID of current example, started from 1. -
dna: The DNA for current example. -
Methods to communicate with the search algorithm:
-
add_measurement: Add a measurement for current example. Multiple measurements can be added as progressive evaluation of the example, which can be used by the early stopping policy to suggest whether current evaluation can be stopped early. done: Mark evaluation on current example as done, use the reward from the latest measurement to feedback to the algorithm, and move to the next example.__call__: A shortcut method that callsadd_measurementanddonein sequence.skip: Mark evaluation on current example as done, and move to the next example without providing feedback to the algorithm.should_stop_early: Tell if progressive evaluation on current example can be stopped early.-
end_loop: Mark the loop as done. All workers will get out of the loop after they finish evaluating their current examples. -
Methods to publish information associated with current trial:
-
set_metadata: Set persistent metadata by key. get_metadata: Get persistent metadata by key.add_link: Add a related link by key.
Source code in pygx/tuning/_protocols.py
checkpoint_to_warm_start_from
abstractmethod
property
¶
Gets checkpoint path to warm start from.
add_measurement
¶
add_measurement(
reward: None | float | Sequence[float] = None,
metrics: dict[str, float] | None = None,
step: int = 0,
checkpoint_path: str | None = None,
elapse_secs: float | None = None,
) -> None
Add a measurement for current trial.
This method can be called multiple times on the same trial, e.g::
for model, feedback in pg.sample(...): accuracy = train_and_evaluate(model, step=10) feedback.add_measurement(accuracy, step=10) accuracy = train_and_evaluate(model, step=15) feedback.add_measurement(accuracy, step=25) feedback.done()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reward
|
None | float | Sequence[float]
|
An optional float value as the reward for single-objective
optimization, or a sequence of float values for multiple objectives
optimization. In multiple-objective scenario, the float sequence will
be paired up with the |
None
|
metrics
|
dict[str, float] | None
|
An optional dictionary of string to float as metrics. It can be used to provide metrics for multi-objective optimization, and/or carry additional metrics for study analysis. |
None
|
step
|
int
|
An optional integer as the step (e.g. step for model training), at which the measurement applies. When a trial is completed, the measurement at the largest step will be chosen as the final measurement to feed back to the controller. |
0
|
checkpoint_path
|
str | None
|
An optional string as the checkpoint path produced from the evaluation (e.g. training a model), which can be used in transfer learning. |
None
|
elapse_secs
|
float | None
|
Time spent on evaluating current example so far. If None, it will be automatically computed by the backend. |
None
|
Source code in pygx/tuning/_protocols.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | |
get_trial
abstractmethod
¶
get_trial() -> Trial
set_metadata
abstractmethod
¶
Sets metadata for current trial or current sampling.
Metadata can be used in two use cases:
- Worker processes that co-work on the same trial can use meta-data to communicate with each other.
- Worker use metadata as a persistent store to save information for
current trial, which can be retrieved via
poll_resultmethod later.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
A string as key to metadata. |
required |
value
|
Any
|
A value that can be serialized by |
required |
per_trial
|
bool
|
If True, the key is set per current trial. Otherwise, it is set per current sampling loop. |
True
|
Source code in pygx/tuning/_protocols.py
get_metadata
abstractmethod
¶
Gets metadata for current trial or current sampling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
A string as key to metadata. |
required |
per_trial
|
bool
|
If True, the key is retrieved per curent trial. Otherwise, it is retrieved per current sampling. |
True
|
Returns:
| Type | Description |
|---|---|
Any | None
|
A value that can be deserialized by |
Source code in pygx/tuning/_protocols.py
add_link
abstractmethod
¶
Adds a related link to current trial.
Added links can be retrieved from the Trial.related_links property via
pg.poll_result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name for the related link. |
required |
url
|
str
|
URL for this link. |
required |
Source code in pygx/tuning/_protocols.py
done
abstractmethod
¶
done(
metadata: dict[str, Any] | None = None,
related_links: dict[str, str] | None = None,
) -> None
Marks current trial as done.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
dict[str, Any] | None
|
Additional metadata to add to current trial. |
None
|
related_links
|
dict[str, str] | None
|
Additional links to add to current trial. |
None
|
Source code in pygx/tuning/_protocols.py
skip
abstractmethod
¶
should_stop_early
abstractmethod
¶
end_loop
abstractmethod
¶
skip_on_exceptions
¶
skip_on_exceptions(
exceptions: Sequence[type[Exception] | tuple[type[Exception], str]],
) -> AbstractContextManager[None]
Returns a context manager to skip trial on user-specified exceptions.
Usages::
with feedback.skip_on_exceptions((ValueError, KeyError)): ...
with feedback.skip_on_exceptions(((ValueError, 'bad value for .'), (ValueError, '. invalid range'), TypeError)): ...
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exceptions
|
Sequence[type[Exception] | tuple[type[Exception], str]]
|
A sequence of (exception type, or exception type plus regular expression for error message). |
required |
Returns:
| Type | Description |
|---|---|
AbstractContextManager[None]
|
A context manager for skipping trials on user-specified exceptions. |
Source code in pygx/tuning/_protocols.py
ignore_race_condition
¶
Context manager for ignoring RaceConditionError within the scope.
Race condition may happen when multiple workers are working on the same trial (e.g. paired train/eval processes). Assuming there are two co-workers (X and Y), common race conditions are:
1) Both X and Y call feedback.done or feedback.skip to the same trial.
2) X calls feedback.done/feedback.skip, then B calls
feedback.add_measurement.
Users can use this context manager to simplify the code for handling
multiple co-workers. (See the group argument of pg.sample)
Usages:: feedback = ... def thread_fun(): with feedback.ignore_race_condition(): feedback.add_measurement(0.1)
# Multiple workers working on the same trial might trigger this code
# from different processes.
feedback.done()
x = threading.Thread(target=thread_fun) x.start() y = threading.Thread(target=thread_fun) y.start()
Yields:
| Type | Description |
|---|---|
None
|
None. |
Source code in pygx/tuning/_protocols.py
Measurement
¶
Measurement(
*,
allow_partial: bool = False,
sealed: bool | None = None,
root_path: KeyPath | None = None,
explicit_init: bool = False,
**kwargs: Any
)
Bases: _DataEntity
Measurement of a trial at certain step.
Source code in pygx/symbolic/_object.py
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 | |
RaceConditionError
¶
Bases: RuntimeError
Race condition error.
This error will be raisen when the operations made to Feedback indicates
a race condition. There are possible scenarios that may lead to such race
conditions, which happen among multiple co-workers (taking X and Y for
example) on the same trial:
- X calls
feedback.done/feedback.skip, then B callsfeedback.add_measurement.
Result
¶
Bases: Formattable
Interface for tuning result.
metadata
abstractmethod
property
¶
Returns the metadata of current sampling.
Trial
¶
Trial(
*,
allow_partial: bool = False,
sealed: bool | None = None,
root_path: KeyPath | None = None,
explicit_init: bool = False,
**kwargs: Any
)
Bases: _DataEntity
Metadata of a trial.
Source code in pygx/symbolic/_object.py
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 | |
get_reward_for_feedback
¶
get_reward_for_feedback(
metric_names: Sequence[str] | None = None,
) -> None | float | tuple[float]
Get reward for feedback.
Source code in pygx/tuning/_protocols.py
add_backend
¶
Decorator to register a backend factory with name.
Source code in pygx/tuning/_backend.py
available_backends
¶
default_backend
¶
set_default_backend
¶
Sets the default tuning backend name.
Source code in pygx/tuning/_backend.py
sample
¶
sample(
space: HyperValue | DynamicEvaluationContext | DNASpec,
algorithm: DNAGenerator,
num_examples: int | None = None,
early_stopping_policy: EarlyStoppingPolicy | None = None,
where: Callable[[HyperPrimitive], bool] | None = None,
name: str | None = None,
group: None | int | str = None,
backend: str | None = None,
metrics_to_optimize: Sequence[str] | None = None,
**kwargs: Any
) -> Iterator[tuple[Any, Feedback]]
Yields an example and its feedback sampled from a hyper value.
Example 1: sample a search space defined by a symbolic hyper value::
for example, feedback in pg.sample( pg.Dict(x=pg.floatv(-1, 1))), pg.geno.Random(), num_examples=10, name='my_search'):
# We can access trial ID (staring from 1) and DNA from the feedback.
print(feedback.id, feedback.dna)
# We can report the reward computed on the example using
# `feedback.add_measurement`, which can be called
# multiple times to report the rewards incrementally.
# Once a trial is done, we call `feedback.done` to mark evaluation on
# current example as completed, or use `feedback.skip` to move to the
# next sample without passing any feedback to the algorithm.
# Without `feedback.done` or `feedback.skip`, the same trial will be
# iterated over and over again for failover handling purpose.
# Besides the reward and the step, metrics and checkpoint can be added
# to each measurement. Additional meta-data and related links (URLs) can
# be passed to `feedback.done` which can be retrieved via
# `pg.poll_result` later.
if example.x >= 0:
# If we only want to add one measurement for each example, a
# shortcut expression for the next two lines can be written as
# follows:
# `feedback(reward=math.sqrt(example.x), step=1)`
feedback.add_measurement(reward=math.sqrt(example.x), step=1)
feedback.done()
else:
feedback.skip()
# IMPORTANT: to stop the loop among all workers, we can call
# `feedback.end_loop`. As a result, each worker will quit their loop
# after current iteration, while using `break` in the for-loop is
# only effective for the local process rather than remotely.
if session.id > 1000:
feedback.end_loop()
# At any time, we can poll the search result via pg.poll_result, please
# see pg.tuning.Result for more details.
result = pg.poll_result('my_search')
print(result.best_trial)
Example 2: sample a search space defined by pg.hyper.trace::
def fun(): return pg.oneof([ lambda: pg.oneof([1, 2, 3]), lambda: pg.float(0.1, 1.0), 3]) + sum(pg.manyof(2, [1, 2, 3]))
for example, feedback in pg.sample(
pg.hyper.trace(fun),
pg.geno.Random(),
num_examples=10,
name='my_search'):
# When space is a pg.hyper.DynamicEvaluationContext object,
# the example yielded at each iteration is a context manager under which
# the hyper primitives (e.g. pg.oneof) will be materialized into concrete
# values according to the controller decision.
with example():
reward = fun()
feedback(reward)
Example 3: sample DNAs from an abstract search space represented by
pg.DNASpec::
for dna, feedback in pg.sample( pg.List([pg.oneof(range(3))] * 5).dna_spec(), pg.geno.Random(), num_examples=10, name='my_search'): reward = evaluate_dna(dna) feedback(reward)
Using pg.sample in distributed environment
pg.sample is designed with distributed sampling in mind, in which multiple
processes can work on the trials of the same sampling loop. While the default
'in-memory' backend works only within a single process without failover
handling, other backends may support distributed computing environment with
persistent state. Nevertheless, the pg.sample API is the same
among different backends, users can switch the backend easily by passing a
different value to the backend argument, or set the default value globally
via pg.tuning.set_default_backend.
Identifying a sampling
To identify a distributed loop, a unique name is introduced, which will
also be used to poll the latest sampling result via pg.poll_result.
Failover handling
In a distributed setup, worker processes may incidentally die and restart.
Unless a trial is explicitly marked as done (via feedback(reward) or
feedback.done()) or skipped (via feedback.skip()), a worker will try to
resume its work on the trial from where it left off.
Workroup
In a distributed setup, worker processes may or may not work on the same
trials. Worker group is introduced to serve this purpose, which is identified
by an integer or a string named group. If group is not specified or
having different values among the workers, every worker will work on
different trials of the loop. On the contrary, workers having the same
group will co-work on the same trials. Group is useful when evaluation on
one example can be parallelized - for example - an example in the outer loop
of a nested search. However, feedback on the same example should be fed back
to the search algorithm only once. Therefore, workers in the same group need
to communicate with each other to avoid duplicated evaluation and feedbacks.
To facilitate such communication, per-trial metadata is supported, and can be
accessed via feedback.set_metadata/get_metadata methods. The consistency in
reading and writing the metadata is defined by the backend used. For the
'in-memory' backend, all the trials and their metadata is stored in memory,
thus will be lost if the process get restarted. On the contrary, the backends
built on distributed computing environment may store both the trials and
metadata in a persistent storage with varing read/write QPS and read/write
consistency guarentees.
Switch between backends
The backend argument of pg.sample lets users choose a backend used in
current sampling loop. Users can use different backends in the same process
to achieve a best performance trade-off, e.g., using in-memory backend when
the communication cost overweighs the redudant evaluation cost upon worker
failure.
Helper function pygx.tuning.set_default_backend is introduced to
set the default tuning backend for the entire process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
space
|
HyperValue | DynamicEvaluationContext | DNASpec
|
One of (a hyper value, a |
required |
algorithm
|
DNAGenerator
|
The search algorithm that samples the search space. For example:
|
required |
num_examples
|
int | None
|
An optional integer as the max number of examples to sample. If None, sample will return an iterator of infinite examples. |
None
|
early_stopping_policy
|
EarlyStoppingPolicy | None
|
An optional early stopping policy for user to tell
if incremental evaluation (which reports multiple measurements) on each
example can be early short circuited.
After each call to |
None
|
where
|
Callable[[HyperPrimitive], bool] | None
|
Function to filter the hyper values. If None, all decision points
from the |
None
|
name
|
str | None
|
A string as a unique identifier for current sampling. Two separate
calls to |
None
|
group
|
None | int | str
|
An string or integer as the group ID of current process in
distributed sampling, which will be used to group different workers into
co-worker groups. Workers with the same group id will work on the same
trial. On the contrary, workers in different groups will always be working
with different trials. If not specified, each worker in current sampling
will be in different groups. |
None
|
backend
|
str | None
|
An optional string to specify the backend name for sampling.
if None, the default backend set by |
None
|
metrics_to_optimize
|
Sequence[str] | None
|
A sequence of string as the names of the metrics to be optimized by the algorithm, which is ['reward'] by default. When specified, it should have only 1 item for single-objective algorithm and can have multiple items for algorithms that support multi-objective optimization. |
None
|
**kwargs
|
Any
|
Arguments passed to the |
{}
|
Yields:
| Type | Description |
|---|---|
Any
|
An iterator of tuples (example, feedback) as examples sampled from the |
Feedback
|
search space defined by the |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in pygx/tuning/_sample.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
options: show_root_heading: false show_root_toc_entry: false members_order: source heading_level: 2