-
Notifications
You must be signed in to change notification settings - Fork 13.7k
/
hyperparameter_tuning_job.py
415 lines (387 loc) · 20.3 KB
/
hyperparameter_tuning_job.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""This module contains a Google Cloud Vertex AI hook."""
from __future__ import annotations
from typing import TYPE_CHECKING, Sequence
from google.api_core.client_options import ClientOptions
from google.api_core.gapic_v1.method import DEFAULT, _MethodDefault
from google.cloud.aiplatform import CustomJob, HyperparameterTuningJob, gapic, hyperparameter_tuning
from google.cloud.aiplatform_v1 import JobServiceClient, types
from airflow.exceptions import AirflowException
from airflow.providers.google.common.hooks.base_google import GoogleBaseHook
if TYPE_CHECKING:
from google.api_core.operation import Operation
from google.api_core.retry import Retry
from google.cloud.aiplatform_v1.services.job_service.pagers import ListHyperparameterTuningJobsPager
class HyperparameterTuningJobHook(GoogleBaseHook):
"""Hook for Google Cloud Vertex AI Hyperparameter Tuning Job APIs."""
def __init__(
self,
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
if kwargs.get("delegate_to") is not None:
raise RuntimeError(
"The `delegate_to` parameter has been deprecated before and finally removed in this version"
" of Google Provider. You MUST convert it to `impersonate_chain`"
)
super().__init__(
gcp_conn_id=gcp_conn_id,
impersonation_chain=impersonation_chain,
)
self._hyperparameter_tuning_job: HyperparameterTuningJob | None = None
def get_job_service_client(self, region: str | None = None) -> JobServiceClient:
"""Returns JobServiceClient."""
if region and region != "global":
client_options = ClientOptions(api_endpoint=f"{region}-aiplatform.googleapis.com:443")
else:
client_options = ClientOptions()
return JobServiceClient(
credentials=self.get_credentials(), client_info=self.client_info, client_options=client_options
)
def get_hyperparameter_tuning_job_object(
self,
display_name: str,
custom_job: CustomJob,
metric_spec: dict[str, str],
parameter_spec: dict[str, hyperparameter_tuning._ParameterSpec],
max_trial_count: int,
parallel_trial_count: int,
max_failed_trial_count: int = 0,
search_algorithm: str | None = None,
measurement_selection: str | None = "best",
project: str | None = None,
location: str | None = None,
labels: dict[str, str] | None = None,
encryption_spec_key_name: str | None = None,
) -> HyperparameterTuningJob:
"""Returns HyperparameterTuningJob object."""
return HyperparameterTuningJob(
display_name=display_name,
custom_job=custom_job,
metric_spec=metric_spec,
parameter_spec=parameter_spec,
max_trial_count=max_trial_count,
parallel_trial_count=parallel_trial_count,
max_failed_trial_count=max_failed_trial_count,
search_algorithm=search_algorithm,
measurement_selection=measurement_selection,
project=project,
location=location,
credentials=self.get_credentials(),
labels=labels,
encryption_spec_key_name=encryption_spec_key_name,
)
def get_custom_job_object(
self,
display_name: str,
worker_pool_specs: list[dict] | list[gapic.WorkerPoolSpec],
base_output_dir: str | None = None,
project: str | None = None,
location: str | None = None,
labels: dict[str, str] | None = None,
encryption_spec_key_name: str | None = None,
staging_bucket: str | None = None,
) -> CustomJob:
"""Returns CustomJob object."""
return CustomJob(
display_name=display_name,
worker_pool_specs=worker_pool_specs,
base_output_dir=base_output_dir,
project=project,
location=location,
credentials=self.get_credentials,
labels=labels,
encryption_spec_key_name=encryption_spec_key_name,
staging_bucket=staging_bucket,
)
@staticmethod
def extract_hyperparameter_tuning_job_id(obj: dict) -> str:
"""Returns unique id of the hyperparameter_tuning_job."""
return obj["name"].rpartition("/")[-1]
def wait_for_operation(self, operation: Operation, timeout: float | None = None):
"""Waits for long-lasting operation to complete."""
try:
return operation.result(timeout=timeout)
except Exception:
error = operation.exception(timeout=timeout)
raise AirflowException(error)
def cancel_hyperparameter_tuning_job(self) -> None:
"""Cancel HyperparameterTuningJob."""
if self._hyperparameter_tuning_job:
self._hyperparameter_tuning_job.cancel()
@GoogleBaseHook.fallback_to_default_project_id
def create_hyperparameter_tuning_job(
self,
project_id: str,
region: str,
display_name: str,
metric_spec: dict[str, str],
parameter_spec: dict[str, hyperparameter_tuning._ParameterSpec],
max_trial_count: int,
parallel_trial_count: int,
# START: CustomJob param
worker_pool_specs: list[dict] | list[gapic.WorkerPoolSpec],
base_output_dir: str | None = None,
custom_job_labels: dict[str, str] | None = None,
custom_job_encryption_spec_key_name: str | None = None,
staging_bucket: str | None = None,
# END: CustomJob param
max_failed_trial_count: int = 0,
search_algorithm: str | None = None,
measurement_selection: str | None = "best",
hyperparameter_tuning_job_labels: dict[str, str] | None = None,
hyperparameter_tuning_job_encryption_spec_key_name: str | None = None,
# START: run param
service_account: str | None = None,
network: str | None = None,
timeout: int | None = None, # seconds
restart_job_on_worker_restart: bool = False,
enable_web_access: bool = False,
tensorboard: str | None = None,
sync: bool = True,
# END: run param
) -> HyperparameterTuningJob:
"""
Create a HyperparameterTuningJob.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param display_name: Required. The user-defined name of the HyperparameterTuningJob. The name can be
up to 128 characters long and can be consist of any UTF-8 characters.
:param metric_spec: Required. Dictionary representing metrics to optimize. The dictionary key is the
metric_id, which is reported by your training job, and the dictionary value is the optimization
goal of the metric('minimize' or 'maximize').
example: metric_spec = {'loss': 'minimize', 'accuracy': 'maximize'}
:param parameter_spec: Required. Dictionary representing parameters to optimize. The dictionary key
is the metric_id, which is passed into your training job as a command line key word argument, and
the dictionary value is the parameter specification of the metric.
:param max_trial_count: Required. The desired total number of Trials.
:param parallel_trial_count: Required. The desired number of Trials to run in parallel.
:param worker_pool_specs: Required. The spec of the worker pools including machine type and Docker
image. Can provided as a list of dictionaries or list of WorkerPoolSpec proto messages.
:param base_output_dir: Optional. GCS output directory of job. If not provided a timestamped
directory in the staging directory will be used.
:param custom_job_labels: Optional. The labels with user-defined metadata to organize CustomJobs.
Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain
lowercase letters, numeric characters, underscores and dashes. International characters are
allowed. See https://goo.gl/xmQnxf for more information and examples of labels.
:param custom_job_encryption_spec_key_name: Optional.Customer-managed encryption key name for a
CustomJob. If this is set, then all resources created by the CustomJob will be encrypted with the
provided encryption key.
:param staging_bucket: Optional. Bucket for produced custom job artifacts. Overrides staging_bucket
set in aiplatform.init.
:param max_failed_trial_count: Optional. The number of failed Trials that need to be seen before
failing the HyperparameterTuningJob. If set to 0, Vertex AI decides how many Trials must fail
before the whole job fails.
:param search_algorithm: The search algorithm specified for the Study. Accepts one of the following:
`None` - If you do not specify an algorithm, your job uses the default Vertex AI algorithm. The
default algorithm applies Bayesian optimization to arrive at the optimal solution with a more
effective search over the parameter space.
'grid' - A simple grid search within the feasible space. This option is particularly useful if
you want to specify a quantity of trials that is greater than the number of points in the
feasible space. In such cases, if you do not specify a grid search, the Vertex AI default
algorithm may generate duplicate suggestions. To use grid search, all parameter specs must be of
type `IntegerParameterSpec`, `CategoricalParameterSpace`, or `DiscreteParameterSpec`.
'random' - A simple random search within the feasible space.
:param measurement_selection: This indicates which measurement to use if/when the service
automatically selects the final measurement from previously reported intermediate measurements.
Accepts: 'best', 'last'
Choose this based on two considerations:
A) Do you expect your measurements to monotonically improve? If so, choose 'last'. On the other
hand, if you're in a situation where your system can "over-train" and you expect the performance
to get better for a while but then start declining, choose 'best'.
B) Are your measurements significantly noisy and/or irreproducible? If so, 'best' will tend to be
over-optimistic, and it may be better to choose 'last'.
If both or neither of (A) and (B) apply, it doesn't matter which selection type is chosen.
:param hyperparameter_tuning_job_labels: Optional. The labels with user-defined metadata to organize
HyperparameterTuningJobs. Label keys and values can be no longer than 64 characters (Unicode
codepoints), can only contain lowercase letters, numeric characters, underscores and dashes.
International characters are allowed. See https://goo.gl/xmQnxf for more information and examples
of labels.
:param hyperparameter_tuning_job_encryption_spec_key_name: Optional. Customer-managed encryption key
options for a HyperparameterTuningJob. If this is set, then all resources created by the
HyperparameterTuningJob will be encrypted with the provided encryption key.
:param service_account: Optional. Specifies the service account for workload run-as account. Users
submitting jobs must have act-as permission on this run-as account.
:param network: Optional. The full name of the Compute Engine network to which the job should be
peered. For example, projects/12345/global/networks/myVPC. Private services access must already
be configured for the network. If left unspecified, the job is not peered with any network.
:param timeout: The maximum job running time in seconds. The default is 7 days.
:param restart_job_on_worker_restart: Restarts the entire CustomJob if a worker gets restarted. This
feature can be used by distributed training jobs that are not resilient to workers leaving and
joining a job.
:param enable_web_access: Whether you want Vertex AI to enable interactive shell access to training
containers. https://cloud.google.com/vertex-ai/docs/training/monitor-debug-interactive-shell
:param tensorboard: Optional. The name of a Vertex AI
[Tensorboard][google.cloud.aiplatform.v1beta1.Tensorboard] resource to which this CustomJob will
upload Tensorboard logs. Format:
``projects/{project}/locations/{location}/tensorboards/{tensorboard}`` The training script should
write Tensorboard to following Vertex AI environment variable: AIP_TENSORBOARD_LOG_DIR
`service_account` is required with provided `tensorboard`. For more information on configuring
your service account please visit:
https://cloud.google.com/vertex-ai/docs/experiments/tensorboard-training
:param sync: Whether to execute this method synchronously. If False, this method will unblock and it
will be executed in a concurrent Future.
"""
custom_job = self.get_custom_job_object(
project=project_id,
location=region,
display_name=display_name,
worker_pool_specs=worker_pool_specs,
base_output_dir=base_output_dir,
labels=custom_job_labels,
encryption_spec_key_name=custom_job_encryption_spec_key_name,
staging_bucket=staging_bucket,
)
self._hyperparameter_tuning_job = self.get_hyperparameter_tuning_job_object(
project=project_id,
location=region,
display_name=display_name,
custom_job=custom_job,
metric_spec=metric_spec,
parameter_spec=parameter_spec,
max_trial_count=max_trial_count,
parallel_trial_count=parallel_trial_count,
max_failed_trial_count=max_failed_trial_count,
search_algorithm=search_algorithm,
measurement_selection=measurement_selection,
labels=hyperparameter_tuning_job_labels,
encryption_spec_key_name=hyperparameter_tuning_job_encryption_spec_key_name,
)
self._hyperparameter_tuning_job.run(
service_account=service_account,
network=network,
timeout=timeout, # seconds
restart_job_on_worker_restart=restart_job_on_worker_restart,
enable_web_access=enable_web_access,
tensorboard=tensorboard,
sync=sync,
)
self._hyperparameter_tuning_job.wait()
return self._hyperparameter_tuning_job
@GoogleBaseHook.fallback_to_default_project_id
def get_hyperparameter_tuning_job(
self,
project_id: str,
region: str,
hyperparameter_tuning_job: str,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> types.HyperparameterTuningJob:
"""
Gets a HyperparameterTuningJob.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param hyperparameter_tuning_job: Required. The name of the HyperparameterTuningJob resource.
:param retry: Designation of what errors, if any, should be retried.
:param timeout: The timeout for this request.
:param metadata: Strings which should be sent along with the request as metadata.
"""
client = self.get_job_service_client(region)
name = client.hyperparameter_tuning_job_path(project_id, region, hyperparameter_tuning_job)
result = client.get_hyperparameter_tuning_job(
request={
"name": name,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
return result
@GoogleBaseHook.fallback_to_default_project_id
def list_hyperparameter_tuning_jobs(
self,
project_id: str,
region: str,
filter: str | None = None,
page_size: int | None = None,
page_token: str | None = None,
read_mask: str | None = None,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> ListHyperparameterTuningJobsPager:
"""
Lists HyperparameterTuningJobs in a Location.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param filter: The standard list filter.
Supported fields:
- ``display_name`` supports = and !=.
- ``state`` supports = and !=.
- ``model_display_name`` supports = and !=
Some examples of using the filter are:
- ``state="JOB_STATE_SUCCEEDED" AND display_name="my_job"``
- ``state="JOB_STATE_RUNNING" OR display_name="my_job"``
- ``NOT display_name="my_job"``
- ``state="JOB_STATE_FAILED"``
:param page_size: The standard list page size.
:param page_token: The standard list page token.
:param read_mask: Mask specifying which fields to read.
:param retry: Designation of what errors, if any, should be retried.
:param timeout: The timeout for this request.
:param metadata: Strings which should be sent along with the request as metadata.
"""
client = self.get_job_service_client(region)
parent = client.common_location_path(project_id, region)
result = client.list_hyperparameter_tuning_jobs(
request={
"parent": parent,
"filter": filter,
"page_size": page_size,
"page_token": page_token,
"read_mask": read_mask,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
return result
@GoogleBaseHook.fallback_to_default_project_id
def delete_hyperparameter_tuning_job(
self,
project_id: str,
region: str,
hyperparameter_tuning_job: str,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
) -> Operation:
"""
Deletes a HyperparameterTuningJob.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param hyperparameter_tuning_job: Required. The name of the HyperparameterTuningJob resource to be
deleted.
:param retry: Designation of what errors, if any, should be retried.
:param timeout: The timeout for this request.
:param metadata: Strings which should be sent along with the request as metadata.
"""
client = self.get_job_service_client(region)
name = client.hyperparameter_tuning_job_path(project_id, region, hyperparameter_tuning_job)
result = client.delete_hyperparameter_tuning_job(
request={
"name": name,
},
retry=retry,
timeout=timeout,
metadata=metadata,
)
return result