-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
artifact_types.py
731 lines (672 loc) · 23.2 KB
/
artifact_types.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
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# Copyright 2021 The Kubeflow Authors. 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.
"""Artifact types corresponding to Google Cloud Resources produced and consumed by GCPC components.
These artifact types can be used in your custom KFP SDK components similarly to
other [KFP SDK
artifacts](https://www.kubeflow.org/docs/components/pipelines/v2/data-types/artifacts/).
If you wish to produce Google artifacts from your own components, it is
recommended that you use [Containerized Python
Components](https://www.kubeflow.org/docs/components/pipelines/v2/components/containerized-python-components/).
You should assign metadata to the Google artifacts according to the artifact's
schema (provided by each artifact's `.schema` attribute).
"""
__all__ = [
'VertexModel',
'VertexEndpoint',
'VertexBatchPredictionJob',
'VertexDataset',
'BQMLModel',
'BQTable',
'UnmanagedContainerModel',
'ClassificationMetrics',
'RegressionMetrics',
'ForecastingMetrics',
]
import textwrap
from typing import Any, Dict, Optional
from kfp import dsl
_RESOURCE_NAME_KEY = 'resourceName'
class VertexModel(dsl.Artifact):
"""An artifact representing a Vertex AI [Model resource](https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.models)."""
schema_title = 'google.VertexModel'
schema_version = '0.0.1'
schema = textwrap.dedent("""\
title: google.VertexModel
type: object
properties:
resourceName:
type: string""")
@classmethod
def create(
cls,
name: str,
uri: str,
model_resource_name: str,
) -> 'VertexModel':
# fmt: off
"""Create a VertexModel artifact instance.
Args:
name: The artifact name.
uri: the Vertex Model resource uri, in a form of https://{service-endpoint}/v1/projects/{project}/locations/{location}/models/{model}, where {service-endpoint} is one of the supported service endpoints at https://cloud.google.com/vertex-ai/docs/reference/rest#rest_endpoints
model_resource_name: The name of the Model resource, in a form of projects/{project}/locations/{location}/models/{model}. For more details, see https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.models/get
Returns:
VertexModel instance.
"""
# fmt: on
return cls(
name=name,
uri=uri,
metadata={_RESOURCE_NAME_KEY: model_resource_name},
)
class VertexEndpoint(dsl.Artifact):
"""An artifact representing a Vertex AI [Endpoint resource](https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.endpoints)."""
schema_title = 'google.VertexEndpoint'
schema_version = '0.0.1'
schema = textwrap.dedent("""\
title: google.VertexEndpoint
type: object
properties:
resourceName:
type: string""")
@classmethod
def create(
cls,
name: str,
uri: str,
endpoint_resource_name: str,
) -> 'VertexEndpoint':
# fmt: off
"""Create a VertexEndpoint artifact instance.
Args:
name: The artifact name.
uri: the Vertex Endpoint resource uri, in a form of https://{service-endpoint}/v1/projects/{project}/locations/{location}/endpoints/{endpoint}, where {service-endpoint} is one of the supported service endpoints at https://cloud.google.com/vertex-ai/docs/reference/rest#rest_endpoints
endpoint_resource_name: The name of the Endpoint resource, in a form of projects/{project}/locations/{location}/endpoints/{endpoint}. For more details, see https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.endpoints/get
Returns:
VertexEndpoint instance.
"""
# fmt: on
return cls(
name=name,
uri=uri,
metadata={_RESOURCE_NAME_KEY: endpoint_resource_name},
)
class VertexBatchPredictionJob(dsl.Artifact):
"""An artifact representing a Vertex AI [BatchPredictionJob resource](https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.batchPredictionJobs#resource:-batchpredictionjob)."""
schema_title = 'google.VertexBatchPredictionJob'
schema_version = '0.0.1'
schema = textwrap.dedent("""\
title: google.VertexBatchPredictionJob
type: object
properties:
resourceName:
type: string
bigqueryOutputTable:
type: string
gcsOutputDirectory:
type: string
bigqueryOutputDataset:
type: string""")
@classmethod
def create(
cls,
name: str,
uri: str,
job_resource_name: str,
bigquery_output_table: Optional[str] = None,
bigquery_output_dataset: Optional[str] = None,
gcs_output_directory: Optional[str] = None,
) -> 'VertexBatchPredictionJob':
# fmt: off
"""Create a VertexBatchPredictionJob artifact instance.
Args:
name: The artifact name.
uri: the Vertex Batch Prediction resource uri, in a form of https://{service-endpoint}/v1/projects/{project}/locations/{location}/batchPredictionJobs/{batchPredictionJob}, where {service-endpoint} is one of the supported service endpoints at https://cloud.google.com/vertex-ai/docs/reference/rest#rest_endpoints
job_resource_name: The name of the batch prediction job resource, in a form of projects/{project}/locations/{location}/batchPredictionJobs/{batchPredictionJob}. For more details, see https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.batchPredictionJobs/get
bigquery_output_table: The name of the BigQuery table created, in predictions_<timestamp> format, into which the prediction output is written. For more details, see https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.batchPredictionJobs#outputinfo
bigquery_output_dataset: The path of the BigQuery dataset created, in bq://projectId.bqDatasetId format, into which the prediction output is written. For more details, see https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.batchPredictionJobs#outputinfo
gcs_output_directory: The full path of the Cloud Storage directory created, into which the prediction output is written. For more details, see https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.batchPredictionJobs#outputinfo
Returns:
VertexBatchPredictionJob instance.
"""
# fmt: on
return cls(
name=name,
uri=uri,
metadata={
_RESOURCE_NAME_KEY: job_resource_name,
'bigqueryOutputTable': bigquery_output_table,
'bigqueryOutputDataset': bigquery_output_dataset,
'gcsOutputDirectory': gcs_output_directory,
},
)
class VertexDataset(dsl.Artifact):
"""An artifact representing a Vertex AI [Dataset resource](https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.datasets)."""
schema_title = 'google.VertexDataset'
schema_version = '0.0.1'
schema = textwrap.dedent("""\
title: google.VertexDataset
type: object
properties:
resourceName:
type: string""")
@classmethod
def create(
cls,
name: str,
uri: str,
dataset_resource_name: str,
) -> 'VertexDataset':
# fmt: off
"""Create a VertexDataset artifact instance.
Args:
name: The artifact name.
uri: the Vertex Dataset resource uri, in a form of https://{service-endpoint}/v1/projects/{project}/locations/{location}/datasets/{datasets_name}, where {service-endpoint} is one of the supported service endpoints at https://cloud.google.com/vertex-ai/docs/reference/rest#rest_endpoints
dataset_resource_name: The name of the Dataset resource, in a form of projects/{project}/locations/{location}/datasets/{datasets_name}. For more details, see https://cloud.google.com/vertex-ai/docs/reference/rest/v1/projects.locations.datasets/get
Returns:
VertexDataset instance.
"""
return cls(
uri=uri,
name=name,
metadata={_RESOURCE_NAME_KEY: dataset_resource_name},
)
class BQMLModel(dsl.Artifact):
"""An artifact representing a Google Cloud [BQML Model resource](https://cloud.google.com/bigquery/docs/reference/rest/v2/models)."""
schema_title = 'google.BQMLModel'
schema_version = '0.0.1'
schema = textwrap.dedent("""\
title: google.BQMLModel
type: object
properties:
projectId:
type: string
datasetId:
type: string
modelId:
type: string""")
@classmethod
def create(
cls,
name: str,
project_id: str,
dataset_id: str,
model_id: str,
) -> 'BQMLModel':
# fmt: off
"""Create a BQMLModel artifact instance.
Args:
name: The artifact name.
project_id: The ID of the project containing this model.
dataset_id: The ID of the dataset containing this model.
model_id: The ID of the model. For more details, see https://cloud.google.com/bigquery/docs/reference/rest/v2/models#ModelReference
Returns:
BQMLModel instance.
"""
# fmt: on
return cls(
name=name,
uri=f'https://www.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}/models/{model_id}',
metadata={
'projectId': project_id,
'datasetId': dataset_id,
'modelId': model_id,
},
)
class BQTable(dsl.Artifact):
"""An artifact representing a Google Cloud [BQ Table resource](https://cloud.google.com/bigquery/docs/reference/rest/v2/tables)."""
schema_title = 'google.BQTable'
schema_version = '0.0.1'
schema = textwrap.dedent("""\
title: google.BQTable
type: object
properties:
projectId:
type: string
datasetId:
type: string
tableId:
type: string
expirationTime:
type: string""")
@classmethod
def create(
cls,
name: str,
project_id: str,
dataset_id: str,
table_id: str,
) -> 'BQTable':
# fmt: off
"""Create a BQTable artifact instance.
Args:
name: The artifact name.
project_id: The ID of the project containing this table.
dataset_id: The ID of the dataset containing this table.
table_id: The ID of the table. For more details, see https://cloud.google.com/bigquery/docs/reference/rest/v2/TableReference
Returns:
BQTable instance.
"""
# fmt: on
return cls(
name=name,
uri=f'https://www.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}/tables/{table_id}',
metadata={
'projectId': project_id,
'datasetId': dataset_id,
'tableId': table_id,
},
)
class UnmanagedContainerModel(dsl.Artifact):
"""An artifact representing a Vertex AI [unmanaged container model](https://cloud.google.com/vertex-ai/docs/reference/rest/v1/ModelContainerSpec)."""
schema_title = 'google.UnmanagedContainerModel'
schema_version = '0.0.1'
schema = textwrap.dedent("""\
title: google.UnmanagedContainerModel
type: object
properties:
predictSchemata:
type: object
properties:
instanceSchemaUri:
type: string
parametersSchemaUri:
type: string
predictionSchemaUri:
type: string
containerSpec:
type: object
properties:
imageUri:
type: string
command:
type: array
items:
type: string
args:
type: array
items:
type: string
env:
type: array
items:
type: object
properties:
name:
type: string
value:
type: string
ports:
type: array
items:
type: object
properties:
containerPort:
type: integer
predictRoute:
type: string
healthRoute:
type: string""")
@classmethod
def create(
cls,
predict_schemata: Dict[str, str],
container_spec: Dict[str, Any],
) -> 'UnmanagedContainerModel':
# fmt: off
"""Create a UnmanagedContainerModel artifact instance.
Args:
predict_schemata: Contains the schemata used in Model's predictions and explanations via PredictionService.Predict, PredictionService.Explain and BatchPredictionJob. For more details, see https://cloud.google.com/vertex-ai/docs/reference/rest/v1/PredictSchemata
container_spec: Specification of a container for serving predictions. Some fields in this message correspond to fields in the Kubernetes Container v1 core specification. For more details, see https://cloud.google.com/vertex-ai/docs/reference/rest/v1/ModelContainerSpec
Returns:
UnmanagedContainerModel instance.
"""
# fmt: on
return cls(
metadata={
'predictSchemata': predict_schemata,
'containerSpec': container_spec,
}
)
class ClassificationMetrics(dsl.Artifact):
"""An artifact representing evaluation [classification metrics](https://cloud.google.com/vertex-ai/docs/tabular-data/classification-regression/evaluate-model#classification_1)."""
schema_title = 'google.ClassificationMetrics'
schema_version = '0.0.1'
schema = textwrap.dedent("""\
title: google.ClassificationMetrics
type: object
properties:
aggregationType:
type: string
enum: - AGGREGATION_TYPE_UNSPECIFIED - MACRO_AVERAGE - MICRO_AVERAGE
aggregationThreshold:
type: number
format: float
recall:
type: number
format: float
precision:
type: number
format: float
f1_score:
type: number
format: float
accuracy:
type: number
format: float
auPrc:
type: number
format: float
auRoc:
type: number
format: float
logLoss:
type: number
format: float
confusionMatrix:
type: object
properties:
rows:
type: array
items:
type: array
items:
type: integer
format: int64
annotationSpecs:
type: array
items:
type: object
properties:
id:
type: string
displayName:
type: string
confidenceMetrics:
type: array
items:
type: object
properties:
confidenceThreshold:
type: number
format: float
recall:
type: number
format: float
precision:
type: number
format: float
f1Score:
type: number
format: float
maxPredictions:
type: integer
format: int32
falsePositiveRate:
type: number
format: float
accuracy:
type: number
format: float
truePositiveCount:
type: integer
format: int64
falsePositiveCount:
type: integer
format: int64
falseNegativeCount:
type: integer
format: int64
trueNegativeCount:
type: integer
format: int64
recallAt1:
type: number
format: float
precisionAt1:
type: number
format: float
falsePositiveRateAt1:
type: number
format: float
f1ScoreAt1:
type: number
format: float
confusionMatrix:
type: object
properties:
rows:
type: array
items:
type: array
items:
type: integer
format: int64
annotationSpecs:
type: array
items:
type: object
properties:
id:
type: string
displayName:
type: string""")
@classmethod
def create(
cls,
name: str = 'evaluation_metrics',
recall: Optional[float] = None,
precision: Optional[float] = None,
f1_score: Optional[float] = None,
accuracy: Optional[float] = None,
au_prc: Optional[float] = None,
au_roc: Optional[float] = None,
log_loss: Optional[float] = None,
) -> 'ClassificationMetrics':
# fmt: off
"""Create a ClassificationMetrics artifact instance.
Args:
name: The artifact name.
recall: Recall (True Positive Rate) for the given confidence threshold.
precision: Precision for the given confidence threshold.
f1_score: The harmonic mean of recall and precision.
accuracy: Accuracy is the fraction of predictions given the correct label.
au_prc: The Area Under Precision-Recall Curve metric.
au_roc: The Area Under Receiver Operating Characteristic curve metric.
log_loss: The Log Loss metric.
Returns:
ClassificationMetrics instance.
"""
# fmt: on
metadata = {}
if recall is not None:
metadata['recall'] = recall
if precision is not None:
metadata['precision'] = precision
if f1_score is not None:
metadata['f1Score'] = f1_score
if accuracy is not None:
metadata['accuracy'] = accuracy
if au_prc is not None:
metadata['auPrc'] = au_prc
if au_roc is not None:
metadata['auRoc'] = au_roc
if log_loss is not None:
metadata['logLoss'] = log_loss
return cls(
name=name,
metadata=metadata,
)
class RegressionMetrics(dsl.Artifact):
"""An artifact representing evaluation [regression metrics](https://cloud.google.com/vertex-ai/docs/tabular-data/classification-regression/evaluate-model#regression_1)."""
schema_title = 'google.RegressionMetrics'
schema_version = '0.0.1'
schema = textwrap.dedent("""\
title: google.RegressionMetrics
type: object
properties:
rootMeanSquaredError:
type: number
format: float
meanAbsoluteError:
type: number
format: float
meanAbsolutePercentageError:
type: number
format: float
rSquared:
type: number
format: float
rootMeanSquaredLogError:
type: number
format: float""")
@classmethod
def create(
cls,
name: str = 'evaluation_metrics',
root_mean_squared_error: Optional[float] = None,
mean_absolute_error: Optional[float] = None,
mean_absolute_percentage_error: Optional[float] = None,
r_squared: Optional[float] = None,
root_mean_squared_log_error: Optional[float] = None,
) -> 'RegressionMetrics':
# fmt: off
"""Create a RegressionMetrics artifact instance.
Args:
name: The artifact name.
root_mean_squared_error: Root Mean Squared Error (RMSE).
mean_absolute_error: Mean Absolute Error (MAE).
mean_absolute_percentage_error: Mean absolute percentage error.
r_squared: Coefficient of determination as Pearson correlation coefficient.
root_mean_squared_log_error: Root mean squared log error.
Returns:
RegressionMetrics instance.
"""
# fmt: on
metadata = {}
if root_mean_squared_error is not None:
metadata['rootMeanSquaredError'] = root_mean_squared_error
if mean_absolute_error is not None:
metadata['meanAbsoluteError'] = mean_absolute_error
if mean_absolute_percentage_error is not None:
metadata['meanAbsolutePercentageError'] = mean_absolute_percentage_error
if r_squared is not None:
metadata['rSquared'] = r_squared
if root_mean_squared_log_error is not None:
metadata['rootMeanSquaredLogError'] = root_mean_squared_log_error
return cls(
name=name,
metadata=metadata,
)
class ForecastingMetrics(dsl.Artifact):
"""An artifact representing evaluation [forecasting metrics](https://cloud.google.com/vertex-ai/docs/tabular-data/forecasting/evaluate-model#metrics)."""
schema_title = 'google.ForecastingMetrics'
schema_version = '0.0.1'
schema = textwrap.dedent("""\
title: google.ForecastingMetrics
type: object
properties:
rootMeanSquaredError:
type: number
format: float
meanAbsoluteError:
type: number
format: float
meanAbsolutePercentageError:
type: number
format: float
rSquared:
type: number
format: float
rootMeanSquaredLogError:
type: number
format: float
weightedAbsolutePercentageError:
type: number
format: float
rootMeanSquaredPercentageError:
type: number
format: float
symmetricMeanAbsolutePercentageError:
type: number
format: float
quantileMetrics:
type: array
items:
type: object
properties:
quantile:
type: number
format: double
scaledPinballLoss:
type: number
format: float
observedQuantile:
type: number
format: double""")
@classmethod
def create(
cls,
name: str = 'evaluation_metrics',
root_mean_squared_error: Optional[float] = None,
mean_absolute_error: Optional[float] = None,
mean_absolute_percentage_error: Optional[float] = None,
r_squared: Optional[float] = None,
root_mean_squared_log_error: Optional[float] = None,
weighted_absolute_percentage_error: Optional[float] = None,
root_mean_squared_percentage_error: Optional[float] = None,
symmetric_mean_absolute_percentage_error: Optional[float] = None,
) -> 'ForecastingMetrics':
# fmt: off
"""Create a ForecastingMetrics artifact instance.
Args:
name: The artifact name.
root_mean_squared_error: Root Mean Squared Error (RMSE).
mean_absolute_error: Mean Absolute Error (MAE).
mean_absolute_percentage_error: Mean absolute percentage error.
r_squared: Coefficient of determination as Pearson correlation coefficient.
root_mean_squared_log_error: Root mean squared log error.
weighted_absolute_percentage_error: Weighted Absolute Percentage Error. Does not use weights, this is just what the metric is called. Undefined if actual values sum to zero. Will be very large if actual values sum to a very small number.
root_mean_squared_percentage_error: Root Mean Square Percentage Error. Square root of MSPE. Undefined/imaginary when MSPE is negative.
symmetric_mean_absolute_percentage_error: Symmetric Mean Absolute Percentage Error.
Returns:
ForecastingMetrics instance.
"""
# fmt: on
metadata = {}
if root_mean_squared_error is not None:
metadata['rootMeanSquaredError'] = root_mean_squared_error
if mean_absolute_error is not None:
metadata['meanAbsoluteError'] = mean_absolute_error
if mean_absolute_percentage_error is not None:
metadata['meanAbsolutePercentageError'] = mean_absolute_percentage_error
if r_squared is not None:
metadata['rSquared'] = r_squared
if root_mean_squared_log_error is not None:
metadata['rootMeanSquaredLogError'] = root_mean_squared_log_error
if weighted_absolute_percentage_error is not None:
metadata['weightedAbsolutePercentageError'] = (
weighted_absolute_percentage_error
)
if root_mean_squared_percentage_error is not None:
metadata['rootMeanSquaredPercentageError'] = (
root_mean_squared_percentage_error
)
if symmetric_mean_absolute_percentage_error is not None:
metadata['symmetricMeanAbsolutePercentageError'] = (
symmetric_mean_absolute_percentage_error
)
return cls(
name=name,
metadata=metadata,
)