-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
create-training-job.ts
450 lines (396 loc) · 15.8 KB
/
create-training-job.ts
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
import { Construct } from 'constructs';
import { AlgorithmSpecification, Channel, InputMode, OutputDataConfig, ResourceConfig, S3DataType, StoppingCondition, VpcConfig } from './base-types';
import { renderEnvironment, renderTags } from './private/utils';
import * as ec2 from '../../../aws-ec2';
import * as iam from '../../../aws-iam';
import * as sfn from '../../../aws-stepfunctions';
import { Duration, Lazy, Size, Stack, Token } from '../../../core';
import { integrationResourceArn, validatePatternSupported } from '../private/task-utils';
/**
* Properties for creating an Amazon SageMaker training job
*
*/
export interface SageMakerCreateTrainingJobProps extends sfn.TaskStateBaseProps {
/**
* Training Job Name.
*/
readonly trainingJobName: string;
/**
* Role for the Training Job. The role must be granted all necessary permissions for the SageMaker training job to
* be able to operate.
*
* See https://docs.aws.amazon.com/fr_fr/sagemaker/latest/dg/sagemaker-roles.html#sagemaker-roles-createtrainingjob-perms
*
* @default - a role will be created.
*/
readonly role?: iam.IRole;
/**
* Identifies the training algorithm to use.
*/
readonly algorithmSpecification: AlgorithmSpecification;
/**
* Isolates the training container. No inbound or outbound network calls can be made to or from the training container.
*
* @default false
*/
readonly enableNetworkIsolation?: boolean;
/**
* Algorithm-specific parameters that influence the quality of the model. Set hyperparameters before you start the learning process.
* For a list of hyperparameters provided by Amazon SageMaker
* @see https://docs.aws.amazon.com/sagemaker/latest/dg/algos.html
*
* @default - No hyperparameters
*/
readonly hyperparameters?: { [key: string]: any };
/**
* Describes the various datasets (e.g. train, validation, test) and the Amazon S3 location where stored.
*/
readonly inputDataConfig: Channel[];
/**
* Tags to be applied to the train job.
*
* @default - No tags
*/
readonly tags?: { [key: string]: string };
/**
* Identifies the Amazon S3 location where you want Amazon SageMaker to save the results of model training.
*/
readonly outputDataConfig: OutputDataConfig;
/**
* Specifies the resources, ML compute instances, and ML storage volumes to deploy for model training.
*
* @default - 1 instance of EC2 `M4.XLarge` with `10GB` volume
*/
readonly resourceConfig?: ResourceConfig;
/**
* Sets a time limit for training.
*
* @default - max runtime of 1 hour
*/
readonly stoppingCondition?: StoppingCondition;
/**
* Specifies the VPC that you want your training job to connect to.
*
* @default - No VPC
*/
readonly vpcConfig?: VpcConfig;
/**
* Environment variables to set in the Docker container.
*
* @default - No environment variables
*/
readonly environment?: { [key: string]: string };
}
/**
* Class representing the SageMaker Create Training Job task.
*
*/
export class SageMakerCreateTrainingJob extends sfn.TaskStateBase implements iam.IGrantable, ec2.IConnectable {
private static readonly SUPPORTED_INTEGRATION_PATTERNS: sfn.IntegrationPattern[] = [
sfn.IntegrationPattern.REQUEST_RESPONSE,
sfn.IntegrationPattern.RUN_JOB,
];
/**
* Allows specify security group connections for instances of this fleet.
*/
public readonly connections: ec2.Connections = new ec2.Connections();
protected readonly taskPolicies?: iam.PolicyStatement[];
protected readonly taskMetrics?: sfn.TaskMetricsConfig;
/**
* The Algorithm Specification
*/
private readonly algorithmSpecification: AlgorithmSpecification;
/**
* The Input Data Config.
*/
private readonly inputDataConfig: Channel[];
/**
* The resource config for the task.
*/
private readonly resourceConfig: ResourceConfig;
/**
* The resource config for the task.
*/
private readonly stoppingCondition: StoppingCondition;
private readonly vpc?: ec2.IVpc;
private securityGroup?: ec2.ISecurityGroup;
private readonly securityGroups: ec2.ISecurityGroup[] = [];
private readonly subnets?: string[];
private readonly integrationPattern: sfn.IntegrationPattern;
private _role?: iam.IRole;
private _grantPrincipal?: iam.IPrincipal;
constructor(scope: Construct, id: string, private readonly props: SageMakerCreateTrainingJobProps) {
super(scope, id, props);
this.integrationPattern = props.integrationPattern || sfn.IntegrationPattern.REQUEST_RESPONSE;
validatePatternSupported(this.integrationPattern, SageMakerCreateTrainingJob.SUPPORTED_INTEGRATION_PATTERNS);
// set the default resource config if not defined.
this.resourceConfig = props.resourceConfig || {
instanceCount: 1,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.M4, ec2.InstanceSize.XLARGE),
volumeSize: Size.gibibytes(10),
};
// set the stopping condition if not defined
this.stoppingCondition = props.stoppingCondition || {
maxRuntime: Duration.hours(1),
};
// check that either algorithm name or image is defined
if (!props.algorithmSpecification.algorithmName && !props.algorithmSpecification.trainingImage) {
throw new Error('Must define either an algorithm name or training image URI in the algorithm specification');
}
// check that both algorithm name and image are not defined
if (props.algorithmSpecification.algorithmName && props.algorithmSpecification.trainingImage) {
throw new Error('Cannot define both an algorithm name and training image URI in the algorithm specification');
}
// validate algorithm name
this.validateAlgorithmName(props.algorithmSpecification.algorithmName);
// set the input mode to 'File' if not defined
this.algorithmSpecification = props.algorithmSpecification.trainingInputMode
? props.algorithmSpecification
: { ...props.algorithmSpecification, trainingInputMode: InputMode.FILE };
// set the S3 Data type of the input data config objects to be 'S3Prefix' if not defined
this.inputDataConfig = props.inputDataConfig.map((config) => {
if (!config.dataSource.s3DataSource.s3DataType) {
return {
...config,
dataSource: { s3DataSource: { ...config.dataSource.s3DataSource, s3DataType: S3DataType.S3_PREFIX } },
};
} else {
return config;
}
});
// add the security groups to the connections object
if (props.vpcConfig) {
this.vpc = props.vpcConfig.vpc;
this.subnets = props.vpcConfig.subnets ? this.vpc.selectSubnets(props.vpcConfig.subnets).subnetIds : this.vpc.selectSubnets().subnetIds;
}
this.taskPolicies = this.makePolicyStatements();
}
/**
* The execution role for the Sagemaker training job.
*
* Only available after task has been added to a state machine.
*/
public get role(): iam.IRole {
if (this._role === undefined) {
throw new Error('role not available yet--use the object in a Task first');
}
return this._role;
}
public get grantPrincipal(): iam.IPrincipal {
if (this._grantPrincipal === undefined) {
throw new Error('Principal not available yet--use the object in a Task first');
}
return this._grantPrincipal;
}
/**
* Add the security group to all instances via the launch configuration
* security groups array.
*
* @param securityGroup: The security group to add
*/
public addSecurityGroup(securityGroup: ec2.ISecurityGroup): void {
this.securityGroups.push(securityGroup);
}
/**
* @internal
*/
protected _renderTask(): any {
return {
Resource: integrationResourceArn('sagemaker', 'createTrainingJob', this.integrationPattern),
Parameters: sfn.FieldUtils.renderObject(this.renderParameters()),
};
}
private renderParameters(): { [key: string]: any } {
return {
TrainingJobName: this.props.trainingJobName,
EnableNetworkIsolation: this.props.enableNetworkIsolation,
RoleArn: this._role!.roleArn,
...this.renderAlgorithmSpecification(this.algorithmSpecification),
...this.renderInputDataConfig(this.inputDataConfig),
...this.renderOutputDataConfig(this.props.outputDataConfig),
...this.renderResourceConfig(this.resourceConfig),
...this.renderStoppingCondition(this.stoppingCondition),
...this.renderHyperparameters(this.props.hyperparameters),
...renderTags(this.props.tags),
...this.renderVpcConfig(this.props.vpcConfig),
...renderEnvironment(this.props.environment),
};
}
private renderAlgorithmSpecification(spec: AlgorithmSpecification): { [key: string]: any } {
return {
AlgorithmSpecification: {
TrainingInputMode: spec.trainingInputMode,
...(spec.trainingImage ? { TrainingImage: spec.trainingImage.bind(this).imageUri } : {}),
...(spec.algorithmName ? { AlgorithmName: spec.algorithmName } : {}),
...(spec.metricDefinitions
? { MetricDefinitions: spec.metricDefinitions.map((metric) => ({ Name: metric.name, Regex: metric.regex })) }
: {}),
},
};
}
private renderInputDataConfig(config: Channel[]): { [key: string]: any } {
return {
InputDataConfig: config.map((channel) => ({
ChannelName: channel.channelName,
DataSource: {
S3DataSource: {
S3Uri: channel.dataSource.s3DataSource.s3Location.bind(this, { forReading: true }).uri,
S3DataType: channel.dataSource.s3DataSource.s3DataType,
...(channel.dataSource.s3DataSource.s3DataDistributionType
? { S3DataDistributionType: channel.dataSource.s3DataSource.s3DataDistributionType }
: {}),
...(channel.dataSource.s3DataSource.attributeNames ? { AttributeNames: channel.dataSource.s3DataSource.attributeNames } : {}),
},
},
...(channel.compressionType ? { CompressionType: channel.compressionType } : {}),
...(channel.contentType ? { ContentType: channel.contentType } : {}),
...(channel.inputMode ? { InputMode: channel.inputMode } : {}),
...(channel.recordWrapperType ? { RecordWrapperType: channel.recordWrapperType } : {}),
})),
};
}
private renderOutputDataConfig(config: OutputDataConfig): { [key: string]: any } {
return {
OutputDataConfig: {
S3OutputPath: config.s3OutputLocation.bind(this, { forWriting: true }).uri,
...(config.encryptionKey ? { KmsKeyId: config.encryptionKey.keyArn } : {}),
},
};
}
private renderResourceConfig(config: ResourceConfig): { [key: string]: any } {
return {
ResourceConfig: {
InstanceCount: config.instanceCount,
InstanceType: sfn.JsonPath.isEncodedJsonPath(config.instanceType.toString())
? config.instanceType.toString() : `ml.${config.instanceType}`,
VolumeSizeInGB: config.volumeSize.toGibibytes(),
...(config.volumeEncryptionKey ? { VolumeKmsKeyId: config.volumeEncryptionKey.keyArn } : {}),
},
};
}
private renderStoppingCondition(config: StoppingCondition): { [key: string]: any } {
return {
StoppingCondition: {
MaxRuntimeInSeconds: config.maxRuntime && config.maxRuntime.toSeconds(),
},
};
}
private renderHyperparameters(params: { [key: string]: any } | undefined): { [key: string]: any } {
return params ? { HyperParameters: params } : {};
}
private renderVpcConfig(config: VpcConfig | undefined): { [key: string]: any } {
return config
? {
VpcConfig: {
SecurityGroupIds: Lazy.list({ produce: () => this.securityGroups.map((sg) => sg.securityGroupId) }),
Subnets: this.subnets,
},
}
: {};
}
private validateAlgorithmName(algorithmName?: string): void {
if (algorithmName === undefined || Token.isUnresolved(algorithmName)) {
return;
}
if (algorithmName.length < 1 || 170 < algorithmName.length) {
throw new Error(`Algorithm name length must be between 1 and 170, but got ${algorithmName.length}`);
}
const regex = /^(arn:aws[a-z\-]*:sagemaker:[a-z0-9\-]*:[0-9]{12}:[a-z\-]*\/)?([a-zA-Z0-9]([a-zA-Z0-9-]){0,62})(?<!-)$/;
if (!regex.test(algorithmName)) {
throw new Error(`Expected algorithm name to match pattern ${regex.source}, but got ${algorithmName}`);
}
}
private makePolicyStatements(): iam.PolicyStatement[] {
// set the sagemaker role or create new one
this._grantPrincipal = this._role =
this.props.role ||
new iam.Role(this, 'SagemakerRole', {
assumedBy: new iam.ServicePrincipal('sagemaker.amazonaws.com'),
inlinePolicies: {
CreateTrainingJob: new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
actions: [
'cloudwatch:PutMetricData',
'logs:CreateLogStream',
'logs:PutLogEvents',
'logs:CreateLogGroup',
'logs:DescribeLogStreams',
'ecr:GetAuthorizationToken',
...(this.props.vpcConfig
? [
'ec2:CreateNetworkInterface',
'ec2:CreateNetworkInterfacePermission',
'ec2:DeleteNetworkInterface',
'ec2:DeleteNetworkInterfacePermission',
'ec2:DescribeNetworkInterfaces',
'ec2:DescribeVpcs',
'ec2:DescribeDhcpOptions',
'ec2:DescribeSubnets',
'ec2:DescribeSecurityGroups',
]
: []),
],
resources: ['*'], // Those permissions cannot be resource-scoped
}),
],
}),
},
});
if (this.props.outputDataConfig.encryptionKey) {
this.props.outputDataConfig.encryptionKey.grantEncrypt(this._role);
}
if (this.props.resourceConfig && this.props.resourceConfig.volumeEncryptionKey) {
this.props.resourceConfig.volumeEncryptionKey.grant(this._role, 'kms:CreateGrant');
}
// create a security group if not defined
if (this.vpc && this.securityGroup === undefined) {
this.securityGroup = new ec2.SecurityGroup(this, 'TrainJobSecurityGroup', {
vpc: this.vpc,
});
this.connections.addSecurityGroup(this.securityGroup);
this.securityGroups.push(this.securityGroup);
}
const stack = Stack.of(this);
// https://docs.aws.amazon.com/step-functions/latest/dg/sagemaker-iam.html
const policyStatements = [
new iam.PolicyStatement({
actions: ['sagemaker:CreateTrainingJob', 'sagemaker:DescribeTrainingJob', 'sagemaker:StopTrainingJob'],
resources: [
stack.formatArn({
service: 'sagemaker',
resource: 'training-job',
// If the job name comes from input, we cannot target the policy to a particular ARN prefix reliably...
resourceName: sfn.JsonPath.isEncodedJsonPath(this.props.trainingJobName) ? '*' : `${this.props.trainingJobName}*`,
}),
],
}),
new iam.PolicyStatement({
actions: ['sagemaker:ListTags'],
resources: ['*'],
}),
new iam.PolicyStatement({
actions: ['iam:PassRole'],
resources: [this._role!.roleArn],
conditions: {
StringEquals: { 'iam:PassedToService': 'sagemaker.amazonaws.com' },
},
}),
];
if (this.integrationPattern === sfn.IntegrationPattern.RUN_JOB) {
policyStatements.push(
new iam.PolicyStatement({
actions: ['events:PutTargets', 'events:PutRule', 'events:DescribeRule'],
resources: [
stack.formatArn({
service: 'events',
resource: 'rule',
resourceName: 'StepFunctionsGetEventsForSageMakerTrainingJobsRule',
}),
],
}),
);
}
return policyStatements;
}
}