-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathmodel.py
2097 lines (1889 loc) · 85.4 KB
/
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) 2024, 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 os
import pathlib
import re
from datetime import datetime, timedelta
from threading import Lock
from typing import Any, Dict, List, Optional, Set, Union
import oci
from cachetools import TTLCache
from huggingface_hub import snapshot_download
from oci.data_science.models import JobRun, Metadata, Model, UpdateModelDetails
from ads.aqua import logger
from ads.aqua.app import AquaApp
from ads.aqua.common.entities import AquaMultiModelRef
from ads.aqua.common.enums import (
ConfigFolder,
CustomInferenceContainerTypeFamily,
FineTuningContainerTypeFamily,
InferenceContainerTypeFamily,
ModelFormat,
Platform,
Tags,
)
from ads.aqua.common.errors import (
AquaFileNotFoundError,
AquaRuntimeError,
AquaValueError,
)
from ads.aqua.common.utils import (
LifecycleStatus,
_build_resource_identifier,
cleanup_local_hf_model_artifact,
create_word_icon,
generate_tei_cmd_var,
get_artifact_path,
get_hf_model_info,
get_preferred_compatible_family,
list_os_files_with_extension,
load_config,
upload_folder,
)
from ads.aqua.config.container_config import AquaContainerConfig, Usage
from ads.aqua.constants import (
AQUA_MODEL_ARTIFACT_CONFIG,
AQUA_MODEL_ARTIFACT_CONFIG_MODEL_NAME,
AQUA_MODEL_ARTIFACT_CONFIG_MODEL_TYPE,
AQUA_MODEL_ARTIFACT_FILE,
AQUA_MODEL_TOKENIZER_CONFIG,
AQUA_MODEL_TYPE_CUSTOM,
HF_METADATA_FOLDER,
LICENSE,
MODEL_BY_REFERENCE_OSS_PATH_KEY,
README,
READY_TO_DEPLOY_STATUS,
READY_TO_FINE_TUNE_STATUS,
READY_TO_IMPORT_STATUS,
TRAINING_METRICS_FINAL,
TRINING_METRICS,
VALIDATION_METRICS,
VALIDATION_METRICS_FINAL,
)
from ads.aqua.model.constants import (
AquaModelMetadataKeys,
FineTuningCustomMetadata,
FineTuningMetricCategories,
ModelCustomMetadataFields,
ModelType,
)
from ads.aqua.model.entities import (
AquaFineTuneModel,
AquaFineTuningMetric,
AquaModel,
AquaModelLicense,
AquaModelReadme,
AquaModelSummary,
ImportModelDetails,
ModelValidationResult,
)
from ads.aqua.model.enums import MultiModelSupportedTaskType
from ads.common.auth import default_signer
from ads.common.oci_resource import SEARCH_TYPE, OCIResource
from ads.common.utils import (
UNKNOWN,
get_console_link,
is_path_exists,
read_file,
)
from ads.config import (
AQUA_DEPLOYMENT_CONTAINER_CMD_VAR_METADATA_NAME,
AQUA_DEPLOYMENT_CONTAINER_METADATA_NAME,
AQUA_DEPLOYMENT_CONTAINER_URI_METADATA_NAME,
AQUA_EVALUATION_CONTAINER_METADATA_NAME,
AQUA_FINETUNING_CONTAINER_METADATA_NAME,
AQUA_SERVICE_MODELS,
COMPARTMENT_OCID,
PROJECT_OCID,
SERVICE,
TENANCY_OCID,
USER,
)
from ads.model import DataScienceModel
from ads.model.common.utils import MetadataArtifactPathType
from ads.model.model_metadata import (
MetadataCustomCategory,
ModelCustomMetadata,
ModelCustomMetadataItem,
)
from ads.telemetry import telemetry
class AquaModelApp(AquaApp):
"""Provides a suite of APIs to interact with Aqua models within the Oracle
Cloud Infrastructure Data Science service, serving as an interface for
managing machine learning models.
Methods
-------
create(model_id: str, project_id: str, compartment_id: str = None, **kwargs) -> "AquaModel"
Creates custom aqua model from service model.
get(model_id: str) -> AquaModel:
Retrieves details of an Aqua model by its unique identifier.
list(compartment_id: str = None, project_id: str = None, **kwargs) -> List[AquaModelSummary]:
Lists all Aqua models within a specified compartment and/or project.
clear_model_list_cache()
Allows clear list model cache items from the service models compartment.
register(model: str, os_path: str, local_dir: str = None)
Note:
This class is designed to work within the Oracle Cloud Infrastructure
and requires proper configuration and authentication set up to interact
with OCI services.
"""
_service_models_cache = TTLCache(
maxsize=10, ttl=timedelta(hours=5), timer=datetime.now
)
# Used for saving service model details
_service_model_details_cache = TTLCache(
maxsize=10, ttl=timedelta(hours=5), timer=datetime.now
)
_cache_lock = Lock()
@telemetry(entry_point="plugin=model&action=create", name="aqua")
def create(
self,
model_id: Union[str, AquaMultiModelRef],
project_id: Optional[str] = None,
compartment_id: Optional[str] = None,
freeform_tags: Optional[Dict] = None,
defined_tags: Optional[Dict] = None,
**kwargs,
) -> DataScienceModel:
"""
Creates a custom Aqua model from a service model.
Parameters
----------
model_id : Union[str, AquaMultiModelRef]
The model ID as a string or a AquaMultiModelRef instance to be deployed.
project_id : Optional[str]
The project ID for the custom model.
compartment_id : Optional[str]
The compartment ID for the custom model. Defaults to None.
If not provided, the compartment ID will be fetched from environment variables.
freeform_tags : Optional[Dict]
Freeform tags for the model.
defined_tags : Optional[Dict]
Defined tags for the model.
Returns
-------
DataScienceModel
The instance of DataScienceModel.
"""
model_id = (
model_id.model_id if isinstance(model_id, AquaMultiModelRef) else model_id
)
service_model = DataScienceModel.from_id(model_id)
target_project = project_id or PROJECT_OCID
target_compartment = compartment_id or COMPARTMENT_OCID
# Skip model copying if it is registered model or fine-tuned model
if (
service_model.freeform_tags.get(Tags.BASE_MODEL_CUSTOM, None) is not None
or service_model.freeform_tags.get(Tags.AQUA_FINE_TUNED_MODEL_TAG)
is not None
):
logger.info(
f"Aqua Model {model_id} already exists in the user's compartment."
"Skipped copying."
)
return service_model
# combine tags
combined_freeform_tags = {
**(service_model.freeform_tags or {}),
**(freeform_tags or {}),
}
combined_defined_tags = {
**(service_model.defined_tags or {}),
**(defined_tags or {}),
}
custom_model = (
DataScienceModel()
.with_compartment_id(target_compartment)
.with_project_id(target_project)
.with_model_file_description(json_dict=service_model.model_file_description)
.with_display_name(service_model.display_name)
.with_description(service_model.description)
.with_freeform_tags(**combined_freeform_tags)
.with_defined_tags(**combined_defined_tags)
.with_custom_metadata_list(service_model.custom_metadata_list)
.with_defined_metadata_list(service_model.defined_metadata_list)
.with_provenance_metadata(service_model.provenance_metadata)
.create(model_by_reference=True, **kwargs)
)
logger.info(
f"Aqua Model {custom_model.id} created with the service model {model_id}."
)
# Track unique models that were created in the user's compartment
self.telemetry.record_event_async(
category="aqua/service/model",
action="create",
detail=service_model.display_name,
)
return custom_model
@telemetry(entry_point="plugin=model&action=create", name="aqua")
def create_multi(
self,
models: List[AquaMultiModelRef],
project_id: Optional[str] = None,
compartment_id: Optional[str] = None,
freeform_tags: Optional[Dict] = None,
defined_tags: Optional[Dict] = None,
**kwargs, # noqa: ARG002
) -> DataScienceModel:
"""
Creates a multi-model grouping using the provided model list.
Parameters
----------
models : List[AquaMultiModelRef]
List of AquaMultiModelRef instances for creating a multi-model group.
project_id : Optional[str]
The project ID for the multi-model group.
compartment_id : Optional[str]
The compartment ID for the multi-model group.
freeform_tags : Optional[Dict]
Freeform tags for the model.
defined_tags : Optional[Dict]
Defined tags for the model.
Returns
-------
DataScienceModel
Instance of DataScienceModel object.
"""
if not models:
raise AquaValueError(
"Model list cannot be empty. Please provide at least one model for deployment."
)
artifact_list = []
display_name_list = []
model_custom_metadata = ModelCustomMetadata()
service_inference_containers = (
self.get_container_config().to_dict().get("inference")
)
supported_container_families = [
container_config_item.family
for container_config_item in service_inference_containers
if any(
usage.upper() in container_config_item.usages
for usage in [Usage.MULTI_MODEL, Usage.OTHER]
)
]
if not supported_container_families:
raise AquaValueError(
"Currently, there are no containers that support multi-model deployment."
)
selected_models_deployment_containers = set()
# Process each model
for model in models:
source_model = DataScienceModel.from_id(model.model_id)
display_name = source_model.display_name
# Update model name in user's input model
model.model_name = model.model_name or display_name
# TODO Uncomment the section below, if only service models should be allowed for multi-model deployment
# if not source_model.freeform_tags.get(Tags.AQUA_SERVICE_MODEL_TAG, UNKNOWN):
# raise AquaValueError(
# f"Invalid selected model {display_name}. "
# "Currently only service models are supported for multi model deployment."
# )
display_name_list.append(display_name)
self._extract_model_task(model, source_model)
# Retrieve model artifact
model_artifact_path = source_model.artifact
if not model_artifact_path:
raise AquaValueError(
f"Model '{display_name}' (ID: {model.model_id}) has no artifacts. "
"Please register the model first."
)
# Update model artifact location in user's input model
model.artifact_location = model_artifact_path
artifact_list.append(model_artifact_path)
# Validate deployment container consistency
deployment_container = source_model.custom_metadata_list.get(
ModelCustomMetadataFields.DEPLOYMENT_CONTAINER,
ModelCustomMetadataItem(
key=ModelCustomMetadataFields.DEPLOYMENT_CONTAINER
),
).value
if deployment_container not in supported_container_families:
raise AquaValueError(
f"Unsupported deployment container '{deployment_container}' for model '{source_model.id}'. "
f"Only '{supported_container_families}' are supported for multi-model deployments."
)
selected_models_deployment_containers.add(deployment_container)
if not selected_models_deployment_containers:
raise AquaValueError(
"None of the selected models are associated with a recognized container family. "
"Please review the selected models, or select a different group of models."
)
# Check if the all models in the group shares same container family
if len(selected_models_deployment_containers) > 1:
deployment_container = get_preferred_compatible_family(
selected_families=selected_models_deployment_containers
)
if not deployment_container:
raise AquaValueError(
"The selected models are associated with different container families: "
f"{list(selected_models_deployment_containers)}."
"For multi-model deployment, all models in the group must share the same container family."
)
else:
deployment_container = selected_models_deployment_containers.pop()
# Generate model group details
timestamp = datetime.now().strftime("%Y%m%d")
model_group_display_name = f"model_group_{timestamp}"
combined_models = ", ".join(display_name_list)
model_group_description = f"Multi-model grouping using {combined_models}."
# Add global metadata
model_custom_metadata.add(
key=ModelCustomMetadataFields.DEPLOYMENT_CONTAINER,
value=deployment_container,
description=f"Inference container mapping for {model_group_display_name}",
category="Other",
)
model_custom_metadata.add(
key=ModelCustomMetadataFields.MULTIMODEL_GROUP_COUNT,
value=str(len(models)),
description="Number of models in the group.",
category="Other",
)
# Combine tags. The `Tags.AQUA_TAG` has been excluded, because we don't want to show
# the models created for multi-model purpose in the AQUA models list.
tags = {
# Tags.AQUA_TAG: "active",
Tags.MULTIMODEL_TYPE_TAG: "true",
**(freeform_tags or {}),
}
# Create multi-model group
custom_model = (
DataScienceModel()
.with_compartment_id(compartment_id)
.with_project_id(project_id)
.with_display_name(model_group_display_name)
.with_description(model_group_description)
.with_freeform_tags(**tags)
.with_defined_tags(**(defined_tags or {}))
.with_custom_metadata_list(model_custom_metadata)
)
# Attach artifacts
for artifact in artifact_list:
custom_model.add_artifact(uri=artifact)
# Finalize creation
custom_model.create(model_by_reference=True)
logger.info(
f"Aqua Model '{custom_model.id}' created with models: {', '.join(display_name_list)}."
)
# Create custom metadata for multi model metadata
custom_model.create_custom_metadata_artifact(
metadata_key_name=ModelCustomMetadataFields.MULTIMODEL_METADATA,
artifact_path_or_content=json.dumps(
[model.model_dump() for model in models]
).encode(),
path_type=MetadataArtifactPathType.CONTENT,
)
logger.debug(
f"Multi model metadata uploaded for Aqua model: {custom_model.id}."
)
# Track telemetry event
self.telemetry.record_event_async(
category="aqua/multimodel",
action="create",
detail=combined_models,
)
return custom_model
@telemetry(entry_point="plugin=model&action=get", name="aqua")
def get(self, model_id: str) -> "AquaModel":
"""Gets the information of an Aqua model.
Parameters
----------
model_id: str
The model OCID.
load_model_card: (bool, optional). Defaults to `True`.
Whether to load model card from artifacts or not.
Returns
-------
AquaModel:
The instance of AquaModel.
"""
cached_item = self._service_model_details_cache.get(model_id)
if cached_item:
logger.info(f"Fetching model details for model {model_id} from cache.")
return cached_item
logger.info(f"Fetching model details for model {model_id}.")
ds_model = DataScienceModel.from_id(model_id)
if not self._if_show(ds_model):
raise AquaRuntimeError(
f"Target model `{ds_model.id} `is not an Aqua model as it does not contain "
f"{Tags.AQUA_TAG} tag."
)
is_fine_tuned_model = bool(
ds_model.freeform_tags
and ds_model.freeform_tags.get(Tags.AQUA_FINE_TUNED_MODEL_TAG)
)
inference_container = ds_model.custom_metadata_list.get(
ModelCustomMetadataFields.DEPLOYMENT_CONTAINER,
ModelCustomMetadataItem(key=ModelCustomMetadataFields.DEPLOYMENT_CONTAINER),
).value
inference_container_uri = ds_model.custom_metadata_list.get(
ModelCustomMetadataFields.DEPLOYMENT_CONTAINER_URI,
ModelCustomMetadataItem(
key=ModelCustomMetadataFields.DEPLOYMENT_CONTAINER_URI
),
).value
evaluation_container = ds_model.custom_metadata_list.get(
ModelCustomMetadataFields.EVALUATION_CONTAINER,
ModelCustomMetadataItem(key=ModelCustomMetadataFields.EVALUATION_CONTAINER),
).value
finetuning_container: str = ds_model.custom_metadata_list.get(
ModelCustomMetadataFields.FINETUNE_CONTAINER,
ModelCustomMetadataItem(key=ModelCustomMetadataFields.FINETUNE_CONTAINER),
).value
artifact_location = ds_model.custom_metadata_list.get(
ModelCustomMetadataFields.ARTIFACT_LOCATION,
ModelCustomMetadataItem(key=ModelCustomMetadataFields.ARTIFACT_LOCATION),
).value
aqua_model_attributes = dict(
**self._process_model(ds_model, self.region),
project_id=ds_model.project_id,
inference_container=inference_container,
inference_container_uri=inference_container_uri,
finetuning_container=finetuning_container,
evaluation_container=evaluation_container,
artifact_location=artifact_location,
)
if not is_fine_tuned_model:
model_details = AquaModel(**aqua_model_attributes)
self._service_model_details_cache.__setitem__(
key=model_id, value=model_details
)
else:
try:
jobrun_ocid = ds_model.provenance_metadata.training_id
jobrun = self.ds_client.get_job_run(jobrun_ocid).data
except Exception as e:
logger.debug(
f"Missing jobrun information in the provenance metadata of the given model {model_id}."
f"\nError: {str(e)}"
)
jobrun = None
try:
source_id = ds_model.custom_metadata_list.get(
FineTuningCustomMetadata.FT_SOURCE
).value
except ValueError as e:
logger.debug(
f"Custom metadata is missing {FineTuningCustomMetadata.FT_SOURCE} key for "
f"model {model_id}.\nError: {str(e)}"
)
source_id = UNKNOWN
try:
source_name = ds_model.custom_metadata_list.get(
FineTuningCustomMetadata.FT_SOURCE_NAME
).value
except ValueError as e:
logger.debug(
f"Custom metadata is missing {FineTuningCustomMetadata.FT_SOURCE_NAME} key for "
f"model {model_id}.\nError: {str(e)}"
)
source_name = UNKNOWN
source_identifier = _build_resource_identifier(
id=source_id,
name=source_name,
region=self.region,
)
ft_metrics = self._build_ft_metrics(ds_model.custom_metadata_list)
job_run_status = (
jobrun.lifecycle_state
if jobrun and jobrun.lifecycle_state != JobRun.LIFECYCLE_STATE_DELETED
else (
JobRun.LIFECYCLE_STATE_SUCCEEDED
if self.if_artifact_exist(ds_model.id)
else JobRun.LIFECYCLE_STATE_FAILED
)
)
# TODO: change the argument's name.
lifecycle_state = LifecycleStatus.get_status(
evaluation_status=ds_model.lifecycle_state,
job_run_status=job_run_status,
)
model_details = AquaFineTuneModel(
**aqua_model_attributes,
source=source_identifier,
lifecycle_state=(
Model.LIFECYCLE_STATE_ACTIVE
if lifecycle_state == JobRun.LIFECYCLE_STATE_SUCCEEDED
else lifecycle_state
),
metrics=ft_metrics,
model=ds_model,
jobrun=jobrun,
region=self.region,
)
return model_details
@telemetry(entry_point="plugin=model&action=delete", name="aqua")
def delete_model(self, model_id):
ds_model = DataScienceModel.from_id(model_id)
is_registered_model = ds_model.freeform_tags.get(Tags.BASE_MODEL_CUSTOM, None)
is_fine_tuned_model = ds_model.freeform_tags.get(
Tags.AQUA_FINE_TUNED_MODEL_TAG, None
)
if is_registered_model or is_fine_tuned_model:
logger.info(f"Deleting model {model_id}.")
return ds_model.delete()
else:
raise AquaRuntimeError(
f"Failed to delete model:{model_id}. Only registered models or finetuned model can be deleted."
)
@telemetry(entry_point="plugin=model&action=edit", name="aqua")
def edit_registered_model(
self, id, inference_container, inference_container_uri, enable_finetuning, task
):
"""Edits the default config of unverified registered model.
Parameters
----------
id: str
The model OCID.
inference_container: str.
The inference container family name
inference_container_uri: str
The inference container uri for embedding models
enable_finetuning: str
Flag to enable or disable finetuning over the model. Defaults to None
task:
The usecase type of the model. e.g , text-generation , text_embedding etc.
Returns
-------
Model:
The instance of oci.data_science.models.Model.
"""
ds_model = DataScienceModel.from_id(id)
if ds_model.freeform_tags.get(Tags.BASE_MODEL_CUSTOM, None):
if ds_model.freeform_tags.get(Tags.AQUA_SERVICE_MODEL_TAG, None):
raise AquaRuntimeError(
"Only registered unverified models can be edited."
)
else:
custom_metadata_list = ds_model.custom_metadata_list
freeform_tags = ds_model.freeform_tags
if inference_container:
if (
inference_container in CustomInferenceContainerTypeFamily
and inference_container_uri is None
):
raise AquaRuntimeError(
"Inference container URI must be provided."
)
else:
custom_metadata_list.add(
key=ModelCustomMetadataFields.DEPLOYMENT_CONTAINER,
value=inference_container,
category=MetadataCustomCategory.OTHER,
description="Deployment container mapping for SMC",
replace=True,
)
if inference_container_uri:
if (
inference_container in CustomInferenceContainerTypeFamily
or inference_container is None
):
custom_metadata_list.add(
key=ModelCustomMetadataFields.DEPLOYMENT_CONTAINER_URI,
value=inference_container_uri,
category=MetadataCustomCategory.OTHER,
description=f"Inference container URI for {ds_model.display_name}",
replace=True,
)
else:
raise AquaRuntimeError(
f"Inference container URI can be edited only with container values: {CustomInferenceContainerTypeFamily.values()}"
)
if enable_finetuning is not None:
if enable_finetuning.lower() == "true":
custom_metadata_list.add(
key=ModelCustomMetadataFields.FINETUNE_CONTAINER,
value=FineTuningContainerTypeFamily.AQUA_FINETUNING_CONTAINER_FAMILY,
category=MetadataCustomCategory.OTHER,
description="Fine-tuning container mapping for SMC",
replace=True,
)
freeform_tags.update({Tags.READY_TO_FINE_TUNE: "true"})
elif enable_finetuning.lower() == "false":
try:
custom_metadata_list.remove(
ModelCustomMetadataFields.FINETUNE_CONTAINER
)
freeform_tags.pop(Tags.READY_TO_FINE_TUNE)
except Exception as ex:
raise AquaRuntimeError(
f"The given model already doesn't support finetuning: {ex}"
) from ex
custom_metadata_list.remove("modelDescription")
if task:
freeform_tags.update({Tags.TASK: task})
updated_custom_metadata_list = [
Metadata(**metadata)
for metadata in custom_metadata_list.to_dict()["data"]
]
update_model_details = UpdateModelDetails(
custom_metadata_list=updated_custom_metadata_list,
freeform_tags=freeform_tags,
)
AquaApp().update_model(id, update_model_details)
logger.info(f"Updated model details for the model {id}.")
else:
raise AquaRuntimeError("Only registered unverified models can be edited.")
def _extract_model_task(
self,
model: AquaMultiModelRef,
source_model: DataScienceModel,
) -> None:
"""In a Multi Model Deployment, will set model_task parameter in AquaMultiModelRef from freeform tags or user"""
# user does not supply model task, we extract from model metadata
if not model.model_task:
model.model_task = source_model.freeform_tags.get(Tags.TASK, UNKNOWN)
task_tag = re.sub(r"-", "_", model.model_task).lower()
# re-visit logic when more model task types are supported
if task_tag in MultiModelSupportedTaskType:
model.model_task = task_tag
else:
raise AquaValueError(
f"Invalid or missing {task_tag} tag for selected model {source_model.display_name}. "
f"Currently only `{MultiModelSupportedTaskType.values()}` models are supported for multi model deployment."
)
def _fetch_metric_from_metadata(
self,
custom_metadata_list: ModelCustomMetadata,
target: str,
category: str,
metric_name: str,
) -> AquaFineTuningMetric:
"""Gets target metric from `ads.model.model_metadata.ModelCustomMetadata`."""
try:
scores = []
for custom_metadata in custom_metadata_list._items:
# We use description to group metrics
if custom_metadata.description == target:
scores.append(custom_metadata.value)
if metric_name.endswith("final"):
break
return AquaFineTuningMetric(
name=metric_name,
category=category,
scores=scores,
)
except Exception:
return AquaFineTuningMetric(name=metric_name, category=category, scores=[])
def _build_ft_metrics(
self, custom_metadata_list: ModelCustomMetadata
) -> List[AquaFineTuningMetric]:
"""Builds Fine Tuning metrics."""
validation_metrics = self._fetch_metric_from_metadata(
custom_metadata_list=custom_metadata_list,
target=FineTuningCustomMetadata.VALIDATION_METRICS_EPOCH,
category=FineTuningMetricCategories.VALIDATION,
metric_name=VALIDATION_METRICS,
)
training_metrics = self._fetch_metric_from_metadata(
custom_metadata_list=custom_metadata_list,
target=FineTuningCustomMetadata.TRAINING_METRICS_EPOCH,
category=FineTuningMetricCategories.TRAINING,
metric_name=TRINING_METRICS,
)
validation_final = self._fetch_metric_from_metadata(
custom_metadata_list=custom_metadata_list,
target=FineTuningCustomMetadata.VALIDATION_METRICS_FINAL,
category=FineTuningMetricCategories.VALIDATION,
metric_name=VALIDATION_METRICS_FINAL,
)
training_final = self._fetch_metric_from_metadata(
custom_metadata_list=custom_metadata_list,
target=FineTuningCustomMetadata.TRAINING_METRICS_FINAL,
category=FineTuningMetricCategories.TRAINING,
metric_name=TRAINING_METRICS_FINAL,
)
return [
validation_metrics,
training_metrics,
validation_final,
training_final,
]
def get_hf_tokenizer_config(self, model_id):
"""
Gets the default model tokenizer config for the given Aqua model.
Returns the content of tokenizer_config.json stored in model artifact.
Parameters
----------
model_id: str
The OCID of the Aqua model.
Returns
-------
Dict:
Model tokenizer config.
"""
config = self.get_config(
model_id, AQUA_MODEL_TOKENIZER_CONFIG, ConfigFolder.ARTIFACT
).config
if not config:
logger.debug(
f"{AQUA_MODEL_TOKENIZER_CONFIG} is not available for the model: {model_id}. "
f"Check if the custom metadata has the artifact path set."
)
return config
return config
@staticmethod
def to_aqua_model(
model: Union[
DataScienceModel,
oci.data_science.models.model.Model,
oci.data_science.models.ModelSummary,
oci.resource_search.models.ResourceSummary,
],
region: str,
) -> AquaModel:
"""Converts a model to an Aqua model."""
return AquaModel(**AquaModelApp._process_model(model, region))
@staticmethod
def _process_model(
model: Union[
DataScienceModel,
oci.data_science.models.model.Model,
oci.data_science.models.ModelSummary,
oci.resource_search.models.ResourceSummary,
],
region: str,
inference_containers: Optional[List[Any]] = None,
) -> dict:
"""Constructs required fields for AquaModelSummary."""
# todo: revisit icon generation code
# icon = self._load_icon(model.display_name)
icon = ""
tags = {}
tags.update(model.defined_tags or {})
tags.update(model.freeform_tags or {})
model_id = (
model.identifier
if isinstance(model, oci.resource_search.models.ResourceSummary)
else model.id
)
console_link = get_console_link(
resource="models",
ocid=model_id,
region=region,
)
description = ""
if isinstance(model, (DataScienceModel, oci.data_science.models.model.Model)):
description = model.description
elif isinstance(model, oci.resource_search.models.ResourceSummary):
description = model.additional_details.get("description")
search_text = (
AquaModelApp._build_search_text(tags=tags, description=description)
if tags
else UNKNOWN
)
freeform_tags = model.freeform_tags or {}
is_fine_tuned_model = Tags.AQUA_FINE_TUNED_MODEL_TAG in freeform_tags
ready_to_deploy = (
freeform_tags.get(Tags.AQUA_TAG, "").upper() == READY_TO_DEPLOY_STATUS
)
ready_to_finetune = (
freeform_tags.get(Tags.READY_TO_FINE_TUNE, "").upper()
== READY_TO_FINE_TUNE_STATUS
)
ready_to_import = (
freeform_tags.get(Tags.READY_TO_IMPORT, "").upper()
== READY_TO_IMPORT_STATUS
)
try:
model_file = model.custom_metadata_list.get(AQUA_MODEL_ARTIFACT_FILE).value
except Exception:
model_file = UNKNOWN
if not inference_containers:
inference_containers = (
AquaApp().get_container_config().to_dict().get("inference")
)
model_formats_str = freeform_tags.get(
Tags.MODEL_FORMAT, ModelFormat.SAFETENSORS
).upper()
model_formats = model_formats_str.split(",")
supported_platform: Set[str] = set()
for container in inference_containers:
for model_format in model_formats:
if model_format in container.model_formats:
supported_platform.update(container.platforms)
nvidia_gpu_supported = Platform.NVIDIA_GPU in supported_platform
arm_cpu_supported = Platform.ARM_CPU in supported_platform
return {
"compartment_id": model.compartment_id,
"icon": icon or UNKNOWN,
"id": model_id,
"license": freeform_tags.get(Tags.LICENSE, UNKNOWN),
"name": model.display_name,
"organization": freeform_tags.get(Tags.ORGANIZATION, UNKNOWN),
"task": freeform_tags.get(Tags.TASK, UNKNOWN),
"time_created": str(model.time_created),
"is_fine_tuned_model": is_fine_tuned_model,
"tags": tags,
"console_link": console_link,
"search_text": search_text,
"ready_to_deploy": ready_to_deploy,
"ready_to_finetune": ready_to_finetune,
"ready_to_import": ready_to_import,
"nvidia_gpu_supported": nvidia_gpu_supported,
"arm_cpu_supported": arm_cpu_supported,
"model_file": model_file,
"model_formats": model_formats,
}
@telemetry(entry_point="plugin=model&action=list", name="aqua")
def list(
self,
compartment_id: str = None,
category: str = None,
project_id: str = None,
model_type: str = None,
**kwargs,
) -> List["AquaModelSummary"]:
"""Lists all Aqua models within a specified compartment and/or project.
If `category` is not specified, the method defaults to returning
the service models within the pre-configured default compartment. By default, the list
of models in the service compartment are cached. Use clear_model_list_cache() to invalidate
the cache.
Parameters
----------
compartment_id: (str, optional). Defaults to `None`.
The compartment OCID.
category: (str,optional). Defaults to `SERVICE`
The category of the models to fetch. Can be either `USER` or `SERVICE`
project_id: (str, optional). Defaults to `None`.
The project OCID.
model_type: (str, optional). Defaults to `None`.
Model type represents the type of model in the user compartment, can be either FT or BASE.
**kwargs:
Additional keyword arguments that can be used to filter the results.
Returns
-------
List[AquaModelSummary]:
The list of the `ads.aqua.model.AquaModelSummary`.
"""
category = category or kwargs.pop("category", SERVICE)
compartment_id = compartment_id or COMPARTMENT_OCID
if category == USER:
# tracks number of times custom model listing was called
self.telemetry.record_event_async(
category="aqua/custom/model", action="list"
)
logger.info(f"Fetching custom models from compartment_id={compartment_id}.")
model_type = model_type.upper() if model_type else ModelType.FT
models = self._rqs(compartment_id, model_type=model_type)
logger.info(
f"Fetched {len(models)} models from {compartment_id or COMPARTMENT_OCID}."
)
else:
# tracks number of times service model listing was called
self.telemetry.record_event_async(
category="aqua/service/model", action="list"
)
if AQUA_SERVICE_MODELS in self._service_models_cache:
logger.info("Returning service models list from cache.")
return self._service_models_cache.get(AQUA_SERVICE_MODELS)
lifecycle_state = kwargs.pop(
"lifecycle_state", Model.LIFECYCLE_STATE_ACTIVE
)
models = self.list_resource(
self.ds_client.list_models,
compartment_id=compartment_id,
lifecycle_state=lifecycle_state,