-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline.py
380 lines (322 loc) · 11.3 KB
/
pipeline.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
"""Example workflow pipeline script for intel pipeline.
. -ModelStep
.
Process-> Train -> Evaluate -> Condition .
.
. -(stop)
Implements a get_pipeline(**kwargs) method.
"""
import os
import boto3
import sagemaker
import sagemaker.session
from sagemaker.inputs import TrainingInput
from sagemaker.model_metrics import (
MetricsSource,
ModelMetrics,
)
from sagemaker.processing import (
ProcessingInput,
ProcessingOutput,
)
from sagemaker.sklearn import SKLearn
from sagemaker.processing import FrameworkProcessor
from sagemaker.pytorch.processing import PyTorchProcessor
from sagemaker.pytorch import PyTorchModel
from sagemaker.workflow.conditions import ConditionGreaterThanOrEqualTo
from sagemaker.workflow.condition_step import (
ConditionStep,
)
from sagemaker.workflow.functions import (
JsonGet,
)
from sagemaker.workflow.parameters import (
ParameterString,
)
from sagemaker.workflow.pipeline import Pipeline
from sagemaker.workflow.properties import PropertyFile
from sagemaker.workflow.steps import (
ProcessingStep,
TrainingStep,
)
from sagemaker.workflow.model_step import ModelStep
from sagemaker.workflow.pipeline_context import PipelineSession
from sagemaker.pytorch import PyTorch
from sagemaker.debugger import TensorBoardOutputConfig
from sagemaker.workflow.steps import (
ProcessingStep,
TrainingStep,
)
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
def get_sagemaker_client(region):
"""Gets the sagemaker client.
Args:
region: the aws region to start the session
default_bucket: the bucket to use for storing the artifacts
Returns:
`sagemaker.session.Session instance
"""
boto_session = boto3.Session(region_name=region)
sagemaker_client = boto_session.client("sagemaker")
return sagemaker_client
def get_session(region, default_bucket):
"""Gets the sagemaker session based on the region.
Args:
region: the aws region to start the session
default_bucket: the bucket to use for storing the artifacts
Returns:
`sagemaker.session.Session instance
"""
boto_session = boto3.Session(region_name=region)
sagemaker_client = boto_session.client("sagemaker")
runtime_client = boto_session.client("sagemaker-runtime")
return sagemaker.session.Session(
boto_session=boto_session,
sagemaker_client=sagemaker_client,
sagemaker_runtime_client=runtime_client,
default_bucket=default_bucket,
)
def get_pipeline_session(region, default_bucket):
"""Gets the pipeline session based on the region.
Args:
region: the aws region to start the session
default_bucket: the bucket to use for storing the artifacts
Returns:
PipelineSession instance
"""
boto_session = boto3.Session(region_name=region)
sagemaker_client = boto_session.client("sagemaker")
return PipelineSession(
boto_session=boto_session,
sagemaker_client=sagemaker_client,
default_bucket=default_bucket,
)
def get_pipeline_custom_tags(new_tags, region, sagemaker_project_arn=None):
try:
sm_client = get_sagemaker_client(region)
response = sm_client.list_tags(
ResourceArn=sagemaker_project_arn)
project_tags = response["Tags"]
for project_tag in project_tags:
new_tags.append(project_tag)
except Exception as e:
print(f"Error getting project tags: {e}")
return new_tags
def get_pipeline(
region,
sagemaker_project_arn=None,
role=None,
default_bucket=None,
model_package_group_name="AbalonePackageGroup",
pipeline_name="AbalonePipeline",
base_job_prefix="Abalone",
processing_instance_type="ml.m5.xlarge",
training_instance_type="ml.m5.xlarge",
):
"""Gets a SageMaker ML Pipeline instance working with on abalone data.
Args:
region: AWS region to create and run the pipeline.
role: IAM role to create and run steps and pipeline.
default_bucket: the bucket to use for storing the artifacts
Returns:
an instance of a pipeline
"""
sagemaker_session = get_session(region, default_bucket)
if role is None:
role = sagemaker.session.get_execution_role(sagemaker_session)
pipeline_session = get_pipeline_session(region, default_bucket)
# [START] Intel pipeline
dvc_repo_url = ParameterString(
name="DVCRepoURL",
default_value="codecommit::ap-south-1://sagemaker-intel"
)
dvc_branch = ParameterString(
name="DVCBranch",
default_value="pipeline-processed-dataset"
)
input_dataset = ParameterString(
name="InputDatasetZip",
default_value="s3://sagemaker-ap-south-1-441249477288/dataset/intel.zip"
)
model_approval_status = ParameterString(
name="ModelApprovalStatus", default_value="PendingManualApproval"
)
base_job_name = base_job_prefix
# PREPROCESS STEP
sklearn_processor = FrameworkProcessor(
estimator_cls=SKLearn,
framework_version="0.23-1",
instance_type="ml.m5.xlarge",
instance_count=1,
image_uri="441249477288.dkr.ecr.ap-south-1.amazonaws.com/sagemaker-training:train",
base_job_name=f"{base_job_name}/preprocess-intel-dataset",
sagemaker_session=pipeline_session,
role=role,
env={
"DVC_REPO_URL": dvc_repo_url,
"DVC_BRANCH": dvc_branch,
"GIT_USER": "gokul-pv",
"GIT_EMAIL": "25975535+gokul-pv@users.noreply.github.com"
}
)
processing_step_args = sklearn_processor.run(
code='preprocess.py',
source_dir=os.path.join(BASE_DIR, "sagemaker_intel"),
inputs=[
ProcessingInput(
input_name='data',
source=input_dataset,
destination='/opt/ml/processing/input'
)
],
outputs=[
ProcessingOutput(
output_name="train",
source="/opt/ml/processing/dataset/train"
),
ProcessingOutput(
output_name="test",
source="/opt/ml/processing/dataset/test"
),
],
)
step_process = ProcessingStep(
name="PreprocessIntelClassifierDataset",
step_args=processing_step_args,
)
# TRAIN STEP
tensorboard_output_config = TensorBoardOutputConfig(
s3_output_path=f's3://{default_bucket}/sagemaker-intel-logs-pipeline',
container_local_output_path='/opt/ml/output/tensorboard'
)
pt_estimator = PyTorch(
base_job_name=f"{base_job_name}/training-intel-pipeline",
image_uri = "441249477288.dkr.ecr.ap-south-1.amazonaws.com/sagemaker-training:train",
source_dir=os.path.join(BASE_DIR, "sagemaker_intel"),
entry_point="train.py",
sagemaker_session=pipeline_session,
role=role,
instance_count=1,
instance_type="ml.g4dn.xlarge",
tensorboard_output_config=tensorboard_output_config,
use_spot_instances=True,
max_wait=1800,
max_run=1500,
environment={
"GIT_USER": "gokul-pv",
"GIT_EMAIL": "25975535+gokul-pv@users.noreply.github.com"
}
)
estimator_step_args = pt_estimator.fit({
'train': TrainingInput(
s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
"train"
].S3Output.S3Uri,
),
'test': TrainingInput(
s3_data=step_process.properties.ProcessingOutputConfig.Outputs[
"test"
].S3Output.S3Uri,
)
})
step_train = TrainingStep(
name="TrainIntelClassifier",
step_args=estimator_step_args,
)
# EVAL STEP
pytorch_processor = PyTorchProcessor(
image_uri = "441249477288.dkr.ecr.ap-south-1.amazonaws.com/sagemaker-training:train",
framework_version='1.11.0',
py_version="py38",
role=role,
sagemaker_session=pipeline_session,
instance_type="ml.m5.4xlarge",
instance_count=1,
base_job_name=f'{base_job_name}/eval-intel-classifier',
)
eval_step_args = pytorch_processor.run(
code='evaluate.py',
source_dir=os.path.join(BASE_DIR, "sagemaker_intel"),
inputs=[
ProcessingInput(
source=step_train.properties.ModelArtifacts.S3ModelArtifacts,
destination="/opt/ml/processing/model",
),
ProcessingInput(
source=step_process.properties.ProcessingOutputConfig.Outputs["test"].S3Output.S3Uri,
destination="/opt/ml/processing/test",
),
],
outputs=[
ProcessingOutput(output_name="evaluation", source="/opt/ml/processing/evaluation"),
],
)
evaluation_report = PropertyFile(
name="IntelClassifierEvaluationReport",
output_name="evaluation",
path="evaluation.json",
)
step_eval = ProcessingStep(
name="EvaluateIntelClassifierModel",
step_args=eval_step_args,
property_files=[evaluation_report],
)
# MODEL REGISTER STEP
model_metrics = ModelMetrics(
model_statistics=MetricsSource(
s3_uri="{}/evaluation.json".format(
step_eval.arguments["ProcessingOutputConfig"]["Outputs"][0]["S3Output"]["S3Uri"]
),
content_type="application/json"
)
)
model = PyTorchModel(
entry_point="infer.py",
source_dir=os.path.join(BASE_DIR, "sagemaker_intel"),
image_uri = "441249477288.dkr.ecr.ap-south-1.amazonaws.com/sagemaker-inference",
sagemaker_session=pipeline_session,
role=role,
model_data=step_train.properties.ModelArtifacts.S3ModelArtifacts,
framework_version="1.11.0",
)
model_step_args = model.register(
content_types=["application/x-npy"],
response_types=["application/json"],
inference_instances=["ml.t2.medium", "ml.t2.large"],
transform_instances=["ml.m4.xlarge"],
model_package_group_name=model_package_group_name,
approval_status=model_approval_status,
model_metrics=model_metrics,
)
step_register = ModelStep(
name="RegisterIntelClassifierModel",
step_args=model_step_args,
)
cond_gte = ConditionGreaterThanOrEqualTo(
left=JsonGet(
step_name=step_eval.name,
property_file=evaluation_report,
json_path="multiclass_classification_metrics.accuracy.value"
),
right=0.6,
)
step_cond = ConditionStep(
name="CheckAccuracyIntelClassifierEvaluation",
conditions=[cond_gte],
if_steps=[step_register],
else_steps=[],
)
# [END] intel pipeline
# pipeline instance
pipeline = Pipeline(
name=pipeline_name,
parameters=[
dvc_repo_url,
dvc_branch,
input_dataset,
model_approval_status
],
steps=[step_process, step_train, step_eval, step_cond],
sagemaker_session=pipeline_session,
)
return pipeline