-
Notifications
You must be signed in to change notification settings - Fork 85
/
deploy.py
261 lines (225 loc) · 8.64 KB
/
deploy.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
# Copyright 2020 Google LLC. All Rights Reserved.
#
# 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, 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.
"""Utilities for deploying jobs to GCP."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import httplib2
import subprocess
import uuid
from googleapiclient import discovery
from googleapiclient import errors
from googleapiclient import http as googleapiclient_http
from . import gcp
from . import machine_config
from .. import version
try:
from tensorflow.python.framework.versions import VERSION
except ImportError:
# Use TF runtime version 2.1 (latest supported) as the default.
# https://cloud.google.com/ai-platform/training/docs/runtime-version-list#tpu-support
VERSION = "2.1"
_USER_AGENT_FOR_TF_CLOUD_TRACKING = "tf-cloud/" + version.__version__
def deploy_job(
region,
image_uri,
chief_config,
worker_count,
worker_config,
entry_point_args,
enable_stream_logs,
job_labels={},
):
"""Deploys job with the given parameters to Google Cloud.
Args:
region: GCP region name.
image_uri: The docker image uri.
chief_config: `MachineConfig` that represents the configuration for
the chief worker in a distribution cluster.
worker_count: Integer that represents the number of general workers
in a distribution cluster. This count does not include the
chief worker.
worker_config: `MachineConfig` that represents the configuration for
the general workers in a distribution cluster.
entry_point_args: Command line arguments to pass to the
`entry_point` program.
enable_stream_logs: Boolean flag which when enabled streams logs
back from the cloud job.
Raises:
RuntimeError, if there was an error submitting the job.
"""
job_id = _generate_job_id()
project_id = gcp.get_project_name()
ml_apis = discovery.build(
"ml", "v1", cache_discovery=False, requestBuilder=TFCloudHttpRequest
)
request_dict = _create_request_dict(
job_id,
region,
image_uri,
chief_config,
worker_count,
worker_config,
entry_point_args,
job_labels=job_labels,
)
try:
response = (
ml_apis.projects()
.jobs()
.create(parent="projects/{}".format(project_id), body=request_dict)
.execute()
)
_print_logs_info(job_id, project_id)
if enable_stream_logs:
_stream_logs(job_id)
except errors.HttpError as err:
raise RuntimeError("There was an error submitting the job." + err._get_reason())
return job_id
def _create_request_dict(
job_id,
region,
image_uri,
chief_config,
worker_count,
worker_config,
entry_point_args,
job_labels={},
):
"""Creates request dictionary for the CAIP training service.
Args:
job_id: String, unique job id.
region: GCP region name.
image_uri: The docker image uri.
chief_config: `MachineConfig` that represents the configuration for
the chief worker in a distribution cluster.
worker_count: Integer that represents the number of general workers
in a distribution cluster. This count does not include the
chief worker.
worker_config: `MachineConfig` that represents the configuration for
the general workers in a distribution cluster.
entry_point_args: Command line arguments to pass to the
`entry_point` program.
job_labels: Dict of str: str. Labels to organize jobs. See
https://cloud.google.com/ai-platform/training/docs/resource-labels.
Returns:
The job request dictionary.
"""
training_input = {}
training_input["region"] = region
training_input["scaleTier"] = "custom"
training_input["masterType"] = gcp.get_machine_type(
chief_config.cpu_cores, chief_config.memory, chief_config.accelerator_type
)
# Set master config
chief_machine_config = {}
chief_machine_config["imageUri"] = image_uri
chief_machine_config["acceleratorConfig"] = {}
chief_machine_config["acceleratorConfig"]["count"] = str(
chief_config.accelerator_count
)
chief_machine_config["acceleratorConfig"]["type"] = gcp.get_accelerator_type(
chief_config.accelerator_type.value
)
training_input["masterConfig"] = chief_machine_config
training_input["workerCount"] = str(worker_count)
if worker_count > 0:
training_input["workerType"] = gcp.get_machine_type(
worker_config.cpu_cores,
worker_config.memory,
worker_config.accelerator_type,
)
worker_machine_config = {}
worker_machine_config["imageUri"] = image_uri
worker_machine_config["acceleratorConfig"] = {}
worker_machine_config["acceleratorConfig"]["count"] = str(
worker_config.accelerator_count
)
worker_machine_config["acceleratorConfig"]["type"] = gcp.get_accelerator_type(
worker_config.accelerator_type.value
)
if machine_config.is_tpu_config(worker_config):
# AI Platform runtime version spec is required for training
# on cloud TPUs.
v = VERSION.split(".")
worker_machine_config["tpuTfVersion"] = v[0] + "." + v[1]
training_input["workerConfig"] = worker_machine_config
if entry_point_args is not None:
training_input["args"] = entry_point_args
# This is temporarily required so that the `TF_CONFIG` generated by
# CAIP uses the keyword 'chief' instead of 'master'.
training_input["use_chief_in_tf_config"] = True
request_dict = {}
request_dict["jobId"] = job_id
request_dict["trainingInput"] = training_input
if job_labels:
request_dict["labels"] = job_labels
return request_dict
def _print_logs_info(job_id, project_id):
"""Prints job id and access url.
Args:
job_id: The job id to print.
project_id: The project id that is used to generate job access url.
"""
print("Job submitted successfully.")
print("Your job ID is: ", job_id)
print("Please access your job logs at the following URL:")
print(
"https://console.cloud.google.com/mlengine/jobs/{}?project={}".format(
job_id, project_id
)
)
def _stream_logs(job_id):
"""Streams job logs to stdout.
Args:
job_id: The job id to stream logs from.
Raises:
RuntimeError: if there are any errors from the streaming subprocess.
"""
try:
print("Streaming job logs: ")
process = subprocess.Popen(
["gcloud", "ai-platform", "jobs", "stream-logs", job_id],
stdout=subprocess.PIPE,
)
while True:
output = process.stdout.readline()
# Break out of the loop when poll returns an exit code.
if process.poll() is not None:
break
if output:
print(output.decode().replace("\x08", ""))
except subprocess.SubprocessError as err:
raise RuntimeError(
"There was an error streaming the job logs. {}".format(err._get_reason())
)
def _generate_job_id():
"""Returns a unique job id prefixed with 'tf_train'."""
# CAIP job id can contains only numbers, letters and underscores.
unique_tag = str(uuid.uuid4()).replace("-", "_")
return "tf_cloud_train_{}".format(unique_tag)
# TODO(pavithrasv): Move this and the discovery API stuff into common repo tools.
class TFCloudHttpRequest(googleapiclient_http.HttpRequest):
"""HttpRequest builder that sets a customized user-agent header for TF Cloud.
This is used to track the usage of the TF Cloud.
"""
def __init__(self, *args, **kwargs):
"""Construct a HttpRequest.
Args:
*args: Positional arguments to pass to the base class constructor.
**kwargs: Keyword arguments to pass to the base class constructor.
"""
headers = kwargs.setdefault("headers", {})
headers["user-agent"] = _USER_AGENT_FOR_TF_CLOUD_TRACKING
super(TFCloudHttpRequest, self).__init__(*args, **kwargs)