-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathdatascience_model.py
2566 lines (2212 loc) · 93.1 KB
/
datascience_model.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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright (c) 2022, 2025 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
import json
import logging
import os
import shutil
import tempfile
from copy import deepcopy
from typing import Dict, List, Optional, Tuple, Union
import pandas
import yaml
from jsonschema import ValidationError, validate
from ads.common import oci_client as oc
from ads.common import utils
from ads.common.extended_enum import ExtendedEnum
from ads.common.object_storage_details import ObjectStorageDetails
from ads.common.utils import is_path_exists
from ads.config import (
AQUA_SERVICE_MODELS_BUCKET as SERVICE_MODELS_BUCKET,
)
from ads.config import (
COMPARTMENT_OCID,
PROJECT_OCID,
USER,
)
from ads.feature_engineering.schema import Schema
from ads.jobs.builders.base import Builder
from ads.model.artifact_downloader import (
LargeArtifactDownloader,
SmallArtifactDownloader,
)
from ads.model.artifact_uploader import LargeArtifactUploader, SmallArtifactUploader
from ads.model.common.utils import MetadataArtifactPathType
from ads.model.model_metadata import (
MetadataCustomCategory,
ModelCustomMetadata,
ModelCustomMetadataItem,
ModelProvenanceMetadata,
ModelTaxonomyMetadata,
)
from ads.model.service.oci_datascience_model import (
ModelMetadataArtifactDetails,
ModelProvenanceNotFoundError,
OCIDataScienceModel,
)
logger = logging.getLogger(__name__)
_MAX_ARTIFACT_SIZE_IN_BYTES = 2147483648 # 2GB
MODEL_BY_REFERENCE_VERSION = "1.0"
MODEL_BY_REFERENCE_JSON_FILE_NAME = "model_description.json"
class ModelArtifactSizeError(Exception): # pragma: no cover
def __init__(self, max_artifact_size: str):
super().__init__(
f"The model artifacts size is greater than `{max_artifact_size}`. "
"The `bucket_uri` needs to be specified to "
"copy artifacts to the object storage bucket. "
"Example: `bucket_uri=oci://<bucket_name>@<namespace>/prefix/`"
)
class BucketNotVersionedError(Exception): # pragma: no cover
def __init__(
self,
msg="Model artifact bucket is not versioned. Enable versioning on the bucket to proceed with model creation by reference.",
):
super().__init__(msg)
class PathNotFoundError(Exception):
def __init__(self, msg="The given path doesn't exist."):
super().__init__(msg)
class ModelFileDescriptionError(Exception): # pragma: no cover
def __init__(self, msg="Model File Description file is not set up."):
super().__init__(msg)
class InvalidArtifactType(Exception): # pragma: no cover
pass
class CustomerNotificationType(ExtendedEnum):
NONE = "NONE"
ALL = "ALL"
ON_FAILURE = "ON_FAILURE"
ON_SUCCESS = "ON_SUCCESS"
class SettingStatus(ExtendedEnum):
"""Enum to represent the status of retention settings."""
PENDING = "PENDING"
SUCCEEDED = "SUCCEEDED"
FAILED = "FAILED"
class ModelBackupSetting:
"""
Class that represents Model Backup Setting Details Metadata.
Methods
-------
to_dict(self) -> Dict:
Serializes the backup settings into a dictionary.
from_dict(cls, data: Dict) -> 'ModelBackupSetting':
Constructs backup settings from a dictionary.
to_json(self) -> str:
Serializes the backup settings into a JSON string.
from_json(cls, json_str: str) -> 'ModelBackupSetting':
Constructs backup settings from a JSON string.
to_yaml(self) -> str:
Serializes the backup settings into a YAML string.
validate(self) -> bool:
Validates the backup settings details.
"""
def __init__(
self,
is_backup_enabled: Optional[bool] = None,
backup_region: Optional[str] = None,
customer_notification_type: Optional[CustomerNotificationType] = None,
):
self.is_backup_enabled = (
is_backup_enabled if is_backup_enabled is not None else False
)
self.backup_region = backup_region
self.customer_notification_type = (
customer_notification_type or CustomerNotificationType.NONE
)
def to_dict(self) -> Dict:
"""Serializes the backup settings into a dictionary."""
return {
"is_backup_enabled": self.is_backup_enabled,
"backup_region": self.backup_region,
"customer_notification_type": self.customer_notification_type,
}
@classmethod
def from_dict(cls, data: Dict) -> "ModelBackupSetting":
"""Constructs backup settings from a dictionary."""
return cls(
is_backup_enabled=data.get("is_backup_enabled"),
backup_region=data.get("backup_region"),
customer_notification_type=data.get("customer_notification_type") or None,
)
def to_json(self) -> str:
"""Serializes the backup settings into a JSON string."""
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str) -> "ModelBackupSetting":
"""Constructs backup settings from a JSON string or dictionary."""
data = json.loads(json_str) if isinstance(json_str, str) else json_str
return cls.from_dict(data)
def to_yaml(self) -> str:
"""Serializes the backup settings into a YAML string."""
return yaml.dump(self.to_dict())
def validate(self) -> bool:
"""Validates the backup settings details. Returns True if valid, False otherwise."""
return all(
[
isinstance(self.is_backup_enabled, bool),
not self.backup_region or isinstance(self.backup_region, str),
isinstance(self.customer_notification_type, str)
and self.customer_notification_type
in CustomerNotificationType.values(),
]
)
def __repr__(self):
return self.to_yaml()
class ModelRetentionSetting:
"""
Class that represents Model Retention Setting Details Metadata.
Methods
-------
to_dict(self) -> Dict:
Serializes the retention settings into a dictionary.
from_dict(cls, data: Dict) -> 'ModelRetentionSetting':
Constructs retention settings from a dictionary.
to_json(self) -> str:
Serializes the retention settings into a JSON string.
from_json(cls, json_str: str) -> 'ModelRetentionSetting':
Constructs retention settings from a JSON string.
to_yaml(self) -> str:
Serializes the retention settings into a YAML string.
validate(self) -> bool:
Validates the retention settings details.
"""
def __init__(
self,
archive_after_days: Optional[int] = None,
delete_after_days: Optional[int] = None,
customer_notification_type: Optional[CustomerNotificationType] = None,
):
self.archive_after_days = archive_after_days
self.delete_after_days = delete_after_days
self.customer_notification_type = (
customer_notification_type or CustomerNotificationType.NONE
)
def to_dict(self) -> Dict:
"""Serializes the retention settings into a dictionary."""
return {
"archive_after_days": self.archive_after_days,
"delete_after_days": self.delete_after_days,
"customer_notification_type": self.customer_notification_type,
}
@classmethod
def from_dict(cls, data: Dict) -> "ModelRetentionSetting":
"""Constructs retention settings from a dictionary."""
return cls(
archive_after_days=data.get("archive_after_days"),
delete_after_days=data.get("delete_after_days"),
customer_notification_type=data.get("customer_notification_type") or None,
)
def to_json(self) -> str:
"""Serializes the retention settings into a JSON string."""
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str) -> "ModelRetentionSetting":
"""Constructs retention settings from a JSON string."""
data = json.loads(json_str) if isinstance(json_str, str) else json_str
return cls.from_dict(data)
def to_yaml(self) -> str:
"""Serializes the retention settings into a YAML string."""
return yaml.dump(self.to_dict())
def validate(self) -> bool:
"""Validates the retention settings details. Returns True if valid, False otherwise."""
return all(
[
self.archive_after_days is None
or (
isinstance(self.archive_after_days, int)
and self.archive_after_days >= 0
),
self.delete_after_days is None
or (
isinstance(self.delete_after_days, int)
and self.delete_after_days >= 0
),
isinstance(self.customer_notification_type, str)
and self.customer_notification_type
in CustomerNotificationType.values(),
]
)
def __repr__(self):
return self.to_yaml()
class ModelRetentionOperationDetails:
"""
Class that represents Model Retention Operation Details Metadata.
Methods
-------
to_dict(self) -> Dict:
Serializes the retention operation details into a dictionary.
from_dict(cls, data: Dict) -> 'ModelRetentionOperationDetails':
Constructs retention operation details from a dictionary.
to_json(self) -> str:
Serializes the retention operation details into a JSON string.
from_json(cls, json_str: str) -> 'ModelRetentionOperationDetails':
Constructs retention operation details from a JSON string.
to_yaml(self) -> str:
Serializes the retention operation details into a YAML string.
validate(self) -> bool:
Validates the retention operation details.
"""
def __init__(
self,
archive_state: Optional[SettingStatus] = None,
archive_state_details: Optional[str] = None,
delete_state: Optional[SettingStatus] = None,
delete_state_details: Optional[str] = None,
time_archival_scheduled: Optional[int] = None,
time_deletion_scheduled: Optional[int] = None,
):
self.archive_state = archive_state
self.archive_state_details = archive_state_details
self.delete_state = delete_state
self.delete_state_details = delete_state_details
self.time_archival_scheduled = time_archival_scheduled
self.time_deletion_scheduled = time_deletion_scheduled
def to_dict(self) -> Dict:
"""Serializes the retention operation details into a dictionary."""
return {
"archive_state": self.archive_state or None,
"archive_state_details": self.archive_state_details,
"delete_state": self.delete_state or None,
"delete_state_details": self.delete_state_details,
"time_archival_scheduled": self.time_archival_scheduled,
"time_deletion_scheduled": self.time_deletion_scheduled,
}
@classmethod
def from_dict(cls, data: Dict) -> "ModelRetentionOperationDetails":
"""Constructs retention operation details from a dictionary."""
return cls(
archive_state=data.get("archive_state") or None,
archive_state_details=data.get("archive_state_details"),
delete_state=data.get("delete_state") or None,
delete_state_details=data.get("delete_state_details"),
time_archival_scheduled=data.get("time_archival_scheduled"),
time_deletion_scheduled=data.get("time_deletion_scheduled"),
)
def to_json(self) -> str:
"""Serializes the retention operation details into a JSON string."""
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> "ModelRetentionOperationDetails":
"""Constructs retention operation details from a JSON string."""
data = json.loads(json_str)
return cls.from_dict(data)
def to_yaml(self) -> str:
"""Serializes the retention operation details into a YAML string."""
return yaml.dump(self.to_dict())
def validate(self) -> bool:
"""Validates the retention operation details."""
return all(
[
self.archive_state is None
or self.archive_state in SettingStatus.values(),
self.delete_state is None
or self.delete_state in SettingStatus.values(),
self.time_archival_scheduled is None
or isinstance(self.time_archival_scheduled, int),
self.time_deletion_scheduled is None
or isinstance(self.time_deletion_scheduled, int),
]
)
def __repr__(self):
return self.to_yaml()
class ModelBackupOperationDetails:
"""
Class that represents Model Backup Operation Details Metadata.
Methods
-------
to_dict(self) -> Dict:
Serializes the backup operation details into a dictionary.
from_dict(cls, data: Dict) -> 'ModelBackupOperationDetails':
Constructs backup operation details from a dictionary.
to_json(self) -> str:
Serializes the backup operation details into a JSON string.
from_json(cls, json_str: str) -> 'ModelBackupOperationDetails':
Constructs backup operation details from a JSON string.
to_yaml(self) -> str:
Serializes the backup operation details into a YAML string.
validate(self) -> bool:
Validates the backup operation details.
"""
def __init__(
self,
backup_state: Optional[SettingStatus] = None,
backup_state_details: Optional[str] = None,
time_last_backup: Optional[int] = None,
):
self.backup_state = backup_state
self.backup_state_details = backup_state_details
self.time_last_backup = time_last_backup
def to_dict(self) -> Dict:
"""Serializes the backup operation details into a dictionary."""
return {
"backup_state": self.backup_state or None,
"backup_state_details": self.backup_state_details,
"time_last_backup": self.time_last_backup,
}
@classmethod
def from_dict(cls, data: Dict) -> "ModelBackupOperationDetails":
"""Constructs backup operation details from a dictionary."""
return cls(
backup_state=data.get("backup_state") or None,
backup_state_details=data.get("backup_state_details"),
time_last_backup=data.get("time_last_backup"),
)
def to_json(self) -> str:
"""Serializes the backup operation details into a JSON string."""
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> "ModelBackupOperationDetails":
"""Constructs backup operation details from a JSON string."""
data = json.loads(json_str)
return cls.from_dict(data)
def to_yaml(self) -> str:
"""Serializes the backup operation details into a YAML string."""
return yaml.dump(self.to_dict())
def validate(self) -> bool:
"""Validates the backup operation details."""
return not (
(
self.backup_state is not None
and self.backup_state not in SettingStatus.values()
)
or (
self.time_last_backup is not None
and not isinstance(self.time_last_backup, int)
)
)
def __repr__(self):
return self.to_yaml()
class DataScienceModel(Builder):
"""Represents a Data Science Model.
Attributes
----------
id: str
Model ID.
project_id: str
Project OCID.
compartment_id: str
Compartment OCID.
name: str
Model name.
description: str
Model description.
freeform_tags: Dict[str, str]
Model freeform tags.
defined_tags: Dict[str, Dict[str, object]]
Model defined tags.
input_schema: ads.feature_engineering.Schema
Model input schema.
output_schema: ads.feature_engineering.Schema, Dict
Model output schema.
defined_metadata_list: ModelTaxonomyMetadata
Model defined metadata.
custom_metadata_list: ModelCustomMetadata
Model custom metadata.
provenance_metadata: ModelProvenanceMetadata
Model provenance metadata.
artifact: str
The artifact location. Can be either path to folder with artifacts or
path to zip archive.
status: Union[str, None]
Model status.
model_version_set_id: str
Model version set ID
version_label: str
Model version label
version_id: str
Model version id
model_file_description: dict
Contains object path details for models created by reference.
backup_setting: ModelBackupSetting
The value to assign to the backup_setting property of this CreateModelDetails.
retention_setting: ModelRetentionSetting
The value to assign to the retention_setting property of this CreateModelDetails.
retention_operation_details: ModelRetentionOperationDetails
The value to assign to the retention_operation_details property for the Model.
backup_operation_details: ModelBackupOperationDetails
The value to assign to the backup_operation_details property for the Model.
Methods
-------
create(self, **kwargs) -> "DataScienceModel"
Creates model.
delete(self, delete_associated_model_deployment: Optional[bool] = False) -> "DataScienceModel":
Removes model.
to_dict(self) -> dict
Serializes model to a dictionary.
from_id(cls, id: str) -> "DataScienceModel"
Gets an existing model by OCID.
from_dict(cls, config: dict) -> "DataScienceModel"
Loads model instance from a dictionary of configurations.
upload_artifact(self, ...) -> None
Uploads model artifacts to the model catalog.
download_artifact(self, ...) -> None
Downloads model artifacts from the model catalog.
update(self, **kwargs) -> "DataScienceModel"
Updates datascience model in model catalog.
list(cls, compartment_id: str = None, **kwargs) -> List["DataScienceModel"]
Lists datascience models in a given compartment.
sync(self):
Sync up a datascience model with OCI datascience model.
with_project_id(self, project_id: str) -> "DataScienceModel"
Sets the project ID.
with_description(self, description: str) -> "DataScienceModel"
Sets the description.
with_compartment_id(self, compartment_id: str) -> "DataScienceModel"
Sets the compartment ID.
with_display_name(self, name: str) -> "DataScienceModel"
Sets the name.
with_freeform_tags(self, **kwargs: Dict[str, str]) -> "DataScienceModel"
Sets freeform tags.
with_defined_tags(self, **kwargs: Dict[str, Dict[str, object]]) -> "DataScienceModel"
Sets defined tags.
with_input_schema(self, schema: Union[Schema, Dict]) -> "DataScienceModel"
Sets the model input schema.
with_output_schema(self, schema: Union[Schema, Dict]) -> "DataScienceModel"
Sets the model output schema.
with_defined_metadata_list(self, metadata: Union[ModelTaxonomyMetadata, Dict]) -> "DataScienceModel"
Sets model taxonomy (defined) metadata.
with_custom_metadata_list(self, metadata: Union[ModelCustomMetadata, Dict]) -> "DataScienceModel"
Sets model custom metadata.
with_provenance_metadata(self, metadata: Union[ModelProvenanceMetadata, Dict]) -> "DataScienceModel"
Sets model provenance metadata.
with_artifact(self, *uri: str)
Sets the artifact location. Can be a local. For models created by reference, uri can take in single arg or multiple args in case
of a fine-tuned or multimodel setting.
with_model_version_set_id(self, model_version_set_id: str):
Sets the model version set ID.
with_version_label(self, version_label: str):
Sets the model version label.
with_version_id(self, version_id: str):
Sets the model version id.
with_model_file_description: dict
Sets path details for models created by reference. Input can be either a dict, string or json file and
the schema is dictated by model_file_description_schema.json
Examples
--------
>>> ds_model = (DataScienceModel()
... .with_compartment_id(os.environ["NB_SESSION_COMPARTMENT_OCID"])
... .with_project_id(os.environ["PROJECT_OCID"])
... .with_display_name("TestModel")
... .with_description("Testing the test model")
... .with_freeform_tags(tag1="val1", tag2="val2")
... .with_artifact("/path/to/the/model/artifacts/"))
>>> ds_model.create()
>>> ds_model.status()
>>> ds_model.with_description("new description").update()
>>> ds_model.download_artifact("/path/to/dst/folder/")
>>> ds_model.delete()
>>> DataScienceModel.list()
"""
_PREFIX = "datascience_model"
CONST_ID = "id"
CONST_PROJECT_ID = "projectId"
CONST_COMPARTMENT_ID = "compartmentId"
CONST_DISPLAY_NAME = "displayName"
CONST_DESCRIPTION = "description"
CONST_FREEFORM_TAG = "freeformTags"
CONST_DEFINED_TAG = "definedTags"
CONST_INPUT_SCHEMA = "inputSchema"
CONST_OUTPUT_SCHEMA = "outputSchema"
CONST_CUSTOM_METADATA = "customMetadataList"
CONST_DEFINED_METADATA = "definedMetadataList"
CONST_PROVENANCE_METADATA = "provenanceMetadata"
CONST_ARTIFACT = "artifact"
CONST_MODEL_VERSION_SET_ID = "modelVersionSetId"
CONST_MODEL_VERSION_SET_NAME = "modelVersionSetName"
CONST_MODEL_VERSION_LABEL = "versionLabel"
CONST_MODEL_VERSION_ID = "versionId"
CONST_TIME_CREATED = "timeCreated"
CONST_LIFECYCLE_STATE = "lifecycleState"
CONST_LIFECYCLE_DETAILS = "lifecycleDetails"
CONST_MODEL_FILE_DESCRIPTION = "modelDescription"
CONST_BACKUP_SETTING = "backupSetting"
CONST_RETENTION_SETTING = "retentionSetting"
CONST_BACKUP_OPERATION_DETAILS = "backupOperationDetails"
CONST_RETENTION_OPERATION_DETAILS = "retentionOperationDetails"
attribute_map = {
CONST_ID: "id",
CONST_PROJECT_ID: "project_id",
CONST_COMPARTMENT_ID: "compartment_id",
CONST_DISPLAY_NAME: "display_name",
CONST_DESCRIPTION: "description",
CONST_FREEFORM_TAG: "freeform_tags",
CONST_DEFINED_TAG: "defined_tags",
CONST_INPUT_SCHEMA: "input_schema",
CONST_OUTPUT_SCHEMA: "output_schema",
CONST_CUSTOM_METADATA: "custom_metadata_list",
CONST_DEFINED_METADATA: "defined_metadata_list",
CONST_PROVENANCE_METADATA: "provenance_metadata",
CONST_ARTIFACT: "artifact",
CONST_MODEL_VERSION_SET_ID: "model_version_set_id",
CONST_MODEL_VERSION_SET_NAME: "model_version_set_name",
CONST_MODEL_VERSION_LABEL: "version_label",
CONST_MODEL_VERSION_ID: "version_id",
CONST_TIME_CREATED: "time_created",
CONST_LIFECYCLE_STATE: "lifecycle_state",
CONST_LIFECYCLE_DETAILS: "lifecycle_details",
CONST_MODEL_FILE_DESCRIPTION: "model_description",
CONST_BACKUP_SETTING: "backup_setting",
CONST_RETENTION_SETTING: "retention_setting",
CONST_BACKUP_OPERATION_DETAILS: "backup_operation_details",
CONST_RETENTION_OPERATION_DETAILS: "retention_operation_details",
}
def __init__(self, spec: Dict = None, **kwargs) -> None:
"""Initializes datascience model.
Parameters
----------
spec: (Dict, optional). Defaults to None.
Object specification.
kwargs: Dict
Specification as keyword arguments.
If 'spec' contains the same key as the one in kwargs,
the value from kwargs will be used.
- project_id: str
- compartment_id: str
- name: str
- description: str
- defined_tags: Dict[str, Dict[str, object]]
- freeform_tags: Dict[str, str]
- input_schema: Union[ads.feature_engineering.Schema, Dict]
- output_schema: Union[ads.feature_engineering.Schema, Dict]
- defined_metadata_list: Union[ModelTaxonomyMetadata, Dict]
- custom_metadata_list: Union[ModelCustomMetadata, Dict]
- provenance_metadata: Union[ModelProvenanceMetadata, Dict]
- artifact: str
"""
super().__init__(spec=spec, **deepcopy(kwargs))
# Reinitiate complex attributes
self._init_complex_attributes()
# Specify oci datascience model instance
self.dsc_model = self._to_oci_dsc_model()
self.local_copy_dir = None
@property
def id(self) -> Optional[str]:
"""The model OCID."""
if self.dsc_model:
return self.dsc_model.id
return None
@property
def status(self) -> Union[str, None]:
"""Status of the model.
Returns
-------
str
Status of the model.
"""
if self.dsc_model:
return self.dsc_model.status
return None
@property
def lifecycle_state(self) -> Union[str, None]:
"""Status of the model.
Returns
-------
str
Status of the model.
"""
if self.dsc_model:
return self.dsc_model.status
return None
@property
def lifecycle_details(self) -> str:
"""
Gets the lifecycle_details of this DataScienceModel.
Details about the lifecycle state of the model.
:return: The lifecycle_details of this DataScienceModel.
:rtype: str
"""
return self.get_spec(self.CONST_LIFECYCLE_DETAILS)
@lifecycle_details.setter
def lifecycle_details(self, lifecycle_details: str) -> "DataScienceModel":
"""
Sets the lifecycle_details of this DataScienceModel.
Details about the lifecycle state of the model.
:param lifecycle_details: The lifecycle_details of this DataScienceModel.
:type: str
"""
return self.set_spec(self.CONST_LIFECYCLE_DETAILS, lifecycle_details)
@property
def kind(self) -> str:
"""The kind of the object as showing in a YAML."""
return "datascienceModel"
@property
def project_id(self) -> str:
return self.get_spec(self.CONST_PROJECT_ID)
def with_project_id(self, project_id: str) -> "DataScienceModel":
"""Sets the project ID.
Parameters
----------
project_id: str
The project ID.
Returns
-------
DataScienceModel
The DataScienceModel instance (self)
"""
return self.set_spec(self.CONST_PROJECT_ID, project_id)
@property
def time_created(self) -> str:
return self.get_spec(self.CONST_TIME_CREATED)
@property
def description(self) -> str:
return self.get_spec(self.CONST_DESCRIPTION)
def with_description(self, description: str) -> "DataScienceModel":
"""Sets the description.
Parameters
----------
description: str
The description of the model.
Returns
-------
DataScienceModel
The DataScienceModel instance (self)
"""
return self.set_spec(self.CONST_DESCRIPTION, description)
@property
def compartment_id(self) -> str:
return self.get_spec(self.CONST_COMPARTMENT_ID)
def with_compartment_id(self, compartment_id: str) -> "DataScienceModel":
"""Sets the compartment ID.
Parameters
----------
compartment_id: str
The compartment ID.
Returns
-------
DataScienceModel
The DataScienceModel instance (self)
"""
return self.set_spec(self.CONST_COMPARTMENT_ID, compartment_id)
@property
def display_name(self) -> str:
return self.get_spec(self.CONST_DISPLAY_NAME)
@display_name.setter
def display_name(self, name: str) -> "DataScienceModel":
return self.set_spec(self.CONST_DISPLAY_NAME, name)
def with_display_name(self, name: str) -> "DataScienceModel":
"""Sets the name.
Parameters
----------
name: str
The name.
Returns
-------
DataScienceModel
The DataScienceModel instance (self)
"""
return self.set_spec(self.CONST_DISPLAY_NAME, name)
@property
def freeform_tags(self) -> Dict[str, str]:
return self.get_spec(self.CONST_FREEFORM_TAG)
def with_freeform_tags(self, **kwargs: Dict[str, str]) -> "DataScienceModel":
"""Sets freeform tags.
Returns
-------
DataScienceModel
The DataScienceModel instance (self)
"""
return self.set_spec(self.CONST_FREEFORM_TAG, kwargs)
@property
def defined_tags(self) -> Dict[str, Dict[str, object]]:
return self.get_spec(self.CONST_DEFINED_TAG)
def with_defined_tags(
self, **kwargs: Dict[str, Dict[str, object]]
) -> "DataScienceModel":
"""Sets defined tags.
Returns
-------
DataScienceModel
The DataScienceModel instance (self)
"""
return self.set_spec(self.CONST_DEFINED_TAG, kwargs)
@property
def input_schema(self) -> Union[Schema, Dict]:
"""Returns model input schema.
Returns
-------
ads.feature_engineering.Schema
Model input schema.
"""
return self.get_spec(self.CONST_INPUT_SCHEMA)
def with_input_schema(self, schema: Union[Schema, Dict]) -> "DataScienceModel":
"""Sets the model input schema.
Parameters
----------
schema: Union[ads.feature_engineering.Schema, Dict]
The model input schema.
Returns
-------
DataScienceModel
The DataScienceModel instance (self)
"""
if schema and isinstance(schema, Dict):
try:
schema = Schema.from_dict(schema)
except Exception as err:
logger.warn(err)
return self.set_spec(self.CONST_INPUT_SCHEMA, schema)
@property
def output_schema(self) -> Union[Schema, Dict]:
"""Returns model output schema.
Returns
-------
ads.feature_engineering.Schema
Model output schema.
"""
return self.get_spec(self.CONST_OUTPUT_SCHEMA)
def with_output_schema(self, schema: Union[Schema, Dict]) -> "DataScienceModel":
"""Sets the model output schema.
Parameters
----------
schema: Union[ads.feature_engineering.Schema, Dict]
The model output schema.
Returns
-------
DataScienceModel
The DataScienceModel instance (self)
"""
if schema and isinstance(schema, Dict):
try:
schema = Schema.from_dict(schema)
except Exception as err:
logger.warn(err)
return self.set_spec(self.CONST_OUTPUT_SCHEMA, schema)
@property
def defined_metadata_list(self) -> ModelTaxonomyMetadata:
"""Returns model taxonomy (defined) metadatda."""
return self.get_spec(self.CONST_DEFINED_METADATA)
def with_defined_metadata_list(
self, metadata: Union[ModelTaxonomyMetadata, Dict]
) -> "DataScienceModel":
"""Sets model taxonomy (defined) metadata.
Parameters
----------
metadata: Union[ModelTaxonomyMetadata, Dict]
The defined metadata.
Returns
-------
DataScienceModel
The DataScienceModel instance (self)
"""
if metadata and isinstance(metadata, Dict):
metadata = ModelTaxonomyMetadata.from_dict(metadata)
return self.set_spec(self.CONST_DEFINED_METADATA, metadata)
@property
def custom_metadata_list(self) -> ModelCustomMetadata:
"""Returns model custom metadatda."""
return self.get_spec(self.CONST_CUSTOM_METADATA)
def with_custom_metadata_list(
self, metadata: Union[ModelCustomMetadata, Dict]
) -> "DataScienceModel":
"""Sets model custom metadata.
Parameters
----------
metadata: Union[ModelCustomMetadata, Dict]
The custom metadata.
Returns
-------
DataScienceModel
The DataScienceModel instance (self)
"""
if metadata and isinstance(metadata, Dict):
metadata = ModelCustomMetadata.from_dict(metadata)
return self.set_spec(self.CONST_CUSTOM_METADATA, metadata)
@property
def provenance_metadata(self) -> ModelProvenanceMetadata:
"""Returns model provenance metadatda."""
return self.get_spec(self.CONST_PROVENANCE_METADATA)
def with_provenance_metadata(
self, metadata: Union[ModelProvenanceMetadata, Dict]
) -> "DataScienceModel":
"""Sets model provenance metadata.
Parameters
----------
provenance_metadata: Union[ModelProvenanceMetadata, Dict]
The provenance metadata.
Returns
-------
DataScienceModel
The DataScienceModel instance (self)
"""
if metadata and isinstance(metadata, Dict):
metadata = ModelProvenanceMetadata.from_dict(metadata)
return self.set_spec(self.CONST_PROVENANCE_METADATA, metadata)
@property
def artifact(self) -> Union[str, list]:
return self.get_spec(self.CONST_ARTIFACT)
def with_artifact(self, uri: str, *args):
"""Sets the artifact location. Can be a local.
Parameters
----------
uri: str
Path to artifact directory or to the ZIP archive.
It could contain a serialized model(required) as well as any files needed for deployment.
The content of the source folder will be zipped and uploaded to the model catalog.
For models created by reference, uri can take in single arg or multiple args in case of a fine-tuned or
multimodel setting.
Examples
--------
>>> .with_artifact(uri="./model1/")
>>> .with_artifact(uri="./model1.zip")
>>> .with_artifact("./model1", "./model2")
"""
return self.set_spec(self.CONST_ARTIFACT, [uri] + list(args) if args else uri)
@property
def model_version_set_id(self) -> str:
return self.get_spec(self.CONST_MODEL_VERSION_SET_ID)
def with_model_version_set_id(self, model_version_set_id: str):
"""Sets the model version set ID.