opsml.cards.model

  1# Copyright (c) Shipt, Inc.
  2# This source code is licensed under the MIT license found in the
  3# LICENSE file in the root directory of this source tree.
  4from pathlib import Path
  5from typing import Any, Dict, Optional
  6from uuid import UUID
  7
  8from pydantic import ConfigDict, SerializeAsAny, field_validator
  9
 10from opsml.cards.base import ArtifactCard
 11from opsml.helpers.logging import ArtifactLogger
 12from opsml.model.interfaces.base import ModelInterface
 13from opsml.types import CardType, ModelCardMetadata, ModelMetadata, OnnxModel
 14
 15logger = ArtifactLogger.get_logger()
 16
 17
 18class ModelCard(ArtifactCard):
 19    """Create a ModelCard from your trained machine learning model.
 20    This Card is used in conjunction with the ModelCardCreator class.
 21
 22    Args:
 23        interface:
 24                Trained model interface.
 25        name:
 26            Name for the model specific to your current project
 27        repository:
 28            Repository that this model is associated with
 29        contact:
 30            Contact to associate with card
 31        info:
 32            `CardInfo` object containing additional metadata. If provided, it will override any
 33            values provided for `name`, `repository`, `contact`, and `version`.
 34
 35            Name, repository, and contact are required arguments for all cards. They can be provided
 36            directly or through a `CardInfo` object.
 37
 38        uid:
 39            Unique id (assigned if card has been registered)
 40        version:
 41            Current version (assigned if card has been registered)
 42        datacard_uid:
 43            Uid of the DataCard associated with training the model
 44        to_onnx:
 45            Whether to convert the model to onnx or not
 46        metadata:
 47            `ModelCardMetadata` associated with the model
 48    """
 49
 50    model_config = ConfigDict(
 51        arbitrary_types_allowed=True,
 52        protected_namespaces=("protect_",),
 53        validate_assignment=True,
 54    )
 55
 56    interface: SerializeAsAny[ModelInterface]
 57    datacard_uid: Optional[str] = None
 58    to_onnx: bool = False
 59    metadata: ModelCardMetadata = ModelCardMetadata()
 60
 61    @field_validator("datacard_uid", mode="before")
 62    @classmethod
 63    def check_uid(cls, datacard_uid: Optional[str] = None) -> Optional[str]:
 64        if datacard_uid is None:
 65            return datacard_uid
 66
 67        try:
 68            UUID(datacard_uid, version=4)  # we use uuid4
 69            return datacard_uid
 70
 71        except ValueError as exc:
 72            raise ValueError("Datacard uid is not a valid uuid") from exc
 73
 74    def load_model(self, **kwargs: Any) -> None:
 75        """Loads model, preprocessor and sample data to interface"""
 76
 77        from opsml.storage.card_loader import ModelCardLoader
 78
 79        ModelCardLoader(self).load_model(**kwargs)
 80
 81    def download_model(self, path: Path, **kwargs: Any) -> None:
 82        """Downloads model, preprocessor and metadata to path
 83
 84        Args:
 85            path:
 86                Path to download model
 87
 88            kwargs:
 89                load_preprocessor:
 90                    Whether to load preprocessor or not. Default is True
 91                load_onnx:
 92                    Whether to load onnx model or not. Default is False
 93                quantize:
 94                    Whether to quantize onnx model or not. Default is False
 95        """
 96
 97        from opsml.storage.card_loader import ModelCardLoader
 98
 99        # set path to download model
100        kwargs["lpath"] = path
101
102        ModelCardLoader(self).download_model(**kwargs)
103
104    def load_onnx_model(self, **kwargs: Any) -> None:
105        """Loads onnx model to interface"""
106
107        from opsml.storage.card_loader import ModelCardLoader
108
109        ModelCardLoader(self).load_onnx_model(**kwargs)
110
111    def load_preprocessor(self, **kwargs: Any) -> None:
112        """Loads onnx model to interface"""
113
114        if self.preprocessor is not None:
115            return
116
117        from opsml.storage.card_loader import ModelCardLoader
118
119        ModelCardLoader(self).load_preprocessor(**kwargs)
120
121    def create_registry_record(self) -> Dict[str, Any]:
122        """Creates a registry record from the current ModelCard"""
123
124        exclude_vars = {"interface": {"model", "preprocessor", "sample_data", "onnx_model"}}
125        dumped_model = self.model_dump(exclude=exclude_vars)
126
127        return dumped_model
128
129    @property
130    def model(self) -> Any:
131        """Quick access to model from interface"""
132        return self.interface.model
133
134    @property
135    def sample_data(self) -> Any:
136        """Quick access to sample data from interface"""
137        return self.interface.sample_data
138
139    @property
140    def preprocessor(self) -> Any:
141        """Quick access to preprocessor from interface"""
142
143        if hasattr(self.interface, "preprocessor"):
144            return self.interface.preprocessor
145
146        if hasattr(self.interface, "tokenizer"):
147            if self.interface.tokenizer is not None:
148                return self.interface.tokenizer
149
150        if hasattr(self.interface, "feature_extractor"):
151            if self.interface.feature_extractor is not None:
152                return self.interface.feature_extractor
153
154        return None
155
156    @property
157    def onnx_model(self) -> Optional[OnnxModel]:
158        """Quick access to onnx model from interface"""
159        return self.interface.onnx_model
160
161    @property
162    def model_metadata(self) -> ModelMetadata:
163        """Loads `ModelMetadata` class"""
164
165        from opsml.storage.card_loader import ModelCardLoader
166
167        return ModelCardLoader(self).load_model_metadata()
168
169    @property
170    def card_type(self) -> str:
171        return CardType.MODELCARD.value
logger = <builtins.Logger object>
class ModelCard(opsml.cards.base.ArtifactCard):
 19class ModelCard(ArtifactCard):
 20    """Create a ModelCard from your trained machine learning model.
 21    This Card is used in conjunction with the ModelCardCreator class.
 22
 23    Args:
 24        interface:
 25                Trained model interface.
 26        name:
 27            Name for the model specific to your current project
 28        repository:
 29            Repository that this model is associated with
 30        contact:
 31            Contact to associate with card
 32        info:
 33            `CardInfo` object containing additional metadata. If provided, it will override any
 34            values provided for `name`, `repository`, `contact`, and `version`.
 35
 36            Name, repository, and contact are required arguments for all cards. They can be provided
 37            directly or through a `CardInfo` object.
 38
 39        uid:
 40            Unique id (assigned if card has been registered)
 41        version:
 42            Current version (assigned if card has been registered)
 43        datacard_uid:
 44            Uid of the DataCard associated with training the model
 45        to_onnx:
 46            Whether to convert the model to onnx or not
 47        metadata:
 48            `ModelCardMetadata` associated with the model
 49    """
 50
 51    model_config = ConfigDict(
 52        arbitrary_types_allowed=True,
 53        protected_namespaces=("protect_",),
 54        validate_assignment=True,
 55    )
 56
 57    interface: SerializeAsAny[ModelInterface]
 58    datacard_uid: Optional[str] = None
 59    to_onnx: bool = False
 60    metadata: ModelCardMetadata = ModelCardMetadata()
 61
 62    @field_validator("datacard_uid", mode="before")
 63    @classmethod
 64    def check_uid(cls, datacard_uid: Optional[str] = None) -> Optional[str]:
 65        if datacard_uid is None:
 66            return datacard_uid
 67
 68        try:
 69            UUID(datacard_uid, version=4)  # we use uuid4
 70            return datacard_uid
 71
 72        except ValueError as exc:
 73            raise ValueError("Datacard uid is not a valid uuid") from exc
 74
 75    def load_model(self, **kwargs: Any) -> None:
 76        """Loads model, preprocessor and sample data to interface"""
 77
 78        from opsml.storage.card_loader import ModelCardLoader
 79
 80        ModelCardLoader(self).load_model(**kwargs)
 81
 82    def download_model(self, path: Path, **kwargs: Any) -> None:
 83        """Downloads model, preprocessor and metadata to path
 84
 85        Args:
 86            path:
 87                Path to download model
 88
 89            kwargs:
 90                load_preprocessor:
 91                    Whether to load preprocessor or not. Default is True
 92                load_onnx:
 93                    Whether to load onnx model or not. Default is False
 94                quantize:
 95                    Whether to quantize onnx model or not. Default is False
 96        """
 97
 98        from opsml.storage.card_loader import ModelCardLoader
 99
100        # set path to download model
101        kwargs["lpath"] = path
102
103        ModelCardLoader(self).download_model(**kwargs)
104
105    def load_onnx_model(self, **kwargs: Any) -> None:
106        """Loads onnx model to interface"""
107
108        from opsml.storage.card_loader import ModelCardLoader
109
110        ModelCardLoader(self).load_onnx_model(**kwargs)
111
112    def load_preprocessor(self, **kwargs: Any) -> None:
113        """Loads onnx model to interface"""
114
115        if self.preprocessor is not None:
116            return
117
118        from opsml.storage.card_loader import ModelCardLoader
119
120        ModelCardLoader(self).load_preprocessor(**kwargs)
121
122    def create_registry_record(self) -> Dict[str, Any]:
123        """Creates a registry record from the current ModelCard"""
124
125        exclude_vars = {"interface": {"model", "preprocessor", "sample_data", "onnx_model"}}
126        dumped_model = self.model_dump(exclude=exclude_vars)
127
128        return dumped_model
129
130    @property
131    def model(self) -> Any:
132        """Quick access to model from interface"""
133        return self.interface.model
134
135    @property
136    def sample_data(self) -> Any:
137        """Quick access to sample data from interface"""
138        return self.interface.sample_data
139
140    @property
141    def preprocessor(self) -> Any:
142        """Quick access to preprocessor from interface"""
143
144        if hasattr(self.interface, "preprocessor"):
145            return self.interface.preprocessor
146
147        if hasattr(self.interface, "tokenizer"):
148            if self.interface.tokenizer is not None:
149                return self.interface.tokenizer
150
151        if hasattr(self.interface, "feature_extractor"):
152            if self.interface.feature_extractor is not None:
153                return self.interface.feature_extractor
154
155        return None
156
157    @property
158    def onnx_model(self) -> Optional[OnnxModel]:
159        """Quick access to onnx model from interface"""
160        return self.interface.onnx_model
161
162    @property
163    def model_metadata(self) -> ModelMetadata:
164        """Loads `ModelMetadata` class"""
165
166        from opsml.storage.card_loader import ModelCardLoader
167
168        return ModelCardLoader(self).load_model_metadata()
169
170    @property
171    def card_type(self) -> str:
172        return CardType.MODELCARD.value

Create a ModelCard from your trained machine learning model. This Card is used in conjunction with the ModelCardCreator class.

Arguments:
  • interface: Trained model interface.
  • name: Name for the model specific to your current project
  • repository: Repository that this model is associated with
  • contact: Contact to associate with card
  • info: CardInfo object containing additional metadata. If provided, it will override any values provided for name, repository, contact, and version.

    Name, repository, and contact are required arguments for all cards. They can be provided directly or through a CardInfo object.

  • uid: Unique id (assigned if card has been registered)
  • version: Current version (assigned if card has been registered)
  • datacard_uid: Uid of the DataCard associated with training the model
  • to_onnx: Whether to convert the model to onnx or not
  • metadata: ModelCardMetadata associated with the model
model_config = {'arbitrary_types_allowed': True, 'validate_assignment': True, 'validate_default': True, 'protected_namespaces': ('protect_',)}
interface: typing.Annotated[opsml.model.interfaces.base.ModelInterface, SerializeAsAny()]
datacard_uid: Optional[str]
to_onnx: bool
metadata: opsml.types.model.ModelCardMetadata
@field_validator('datacard_uid', mode='before')
@classmethod
def check_uid(cls, datacard_uid: Optional[str] = None) -> Optional[str]:
62    @field_validator("datacard_uid", mode="before")
63    @classmethod
64    def check_uid(cls, datacard_uid: Optional[str] = None) -> Optional[str]:
65        if datacard_uid is None:
66            return datacard_uid
67
68        try:
69            UUID(datacard_uid, version=4)  # we use uuid4
70            return datacard_uid
71
72        except ValueError as exc:
73            raise ValueError("Datacard uid is not a valid uuid") from exc
def load_model(self, **kwargs: Any) -> None:
75    def load_model(self, **kwargs: Any) -> None:
76        """Loads model, preprocessor and sample data to interface"""
77
78        from opsml.storage.card_loader import ModelCardLoader
79
80        ModelCardLoader(self).load_model(**kwargs)

Loads model, preprocessor and sample data to interface

def download_model(self, path: pathlib.Path, **kwargs: Any) -> None:
 82    def download_model(self, path: Path, **kwargs: Any) -> None:
 83        """Downloads model, preprocessor and metadata to path
 84
 85        Args:
 86            path:
 87                Path to download model
 88
 89            kwargs:
 90                load_preprocessor:
 91                    Whether to load preprocessor or not. Default is True
 92                load_onnx:
 93                    Whether to load onnx model or not. Default is False
 94                quantize:
 95                    Whether to quantize onnx model or not. Default is False
 96        """
 97
 98        from opsml.storage.card_loader import ModelCardLoader
 99
100        # set path to download model
101        kwargs["lpath"] = path
102
103        ModelCardLoader(self).download_model(**kwargs)

Downloads model, preprocessor and metadata to path

Arguments:
  • path: Path to download model
  • kwargs: load_preprocessor: Whether to load preprocessor or not. Default is True load_onnx: Whether to load onnx model or not. Default is False quantize: Whether to quantize onnx model or not. Default is False
def load_onnx_model(self, **kwargs: Any) -> None:
105    def load_onnx_model(self, **kwargs: Any) -> None:
106        """Loads onnx model to interface"""
107
108        from opsml.storage.card_loader import ModelCardLoader
109
110        ModelCardLoader(self).load_onnx_model(**kwargs)

Loads onnx model to interface

def load_preprocessor(self, **kwargs: Any) -> None:
112    def load_preprocessor(self, **kwargs: Any) -> None:
113        """Loads onnx model to interface"""
114
115        if self.preprocessor is not None:
116            return
117
118        from opsml.storage.card_loader import ModelCardLoader
119
120        ModelCardLoader(self).load_preprocessor(**kwargs)

Loads onnx model to interface

def create_registry_record(self) -> Dict[str, Any]:
122    def create_registry_record(self) -> Dict[str, Any]:
123        """Creates a registry record from the current ModelCard"""
124
125        exclude_vars = {"interface": {"model", "preprocessor", "sample_data", "onnx_model"}}
126        dumped_model = self.model_dump(exclude=exclude_vars)
127
128        return dumped_model

Creates a registry record from the current ModelCard

model: Any
130    @property
131    def model(self) -> Any:
132        """Quick access to model from interface"""
133        return self.interface.model

Quick access to model from interface

sample_data: Any
135    @property
136    def sample_data(self) -> Any:
137        """Quick access to sample data from interface"""
138        return self.interface.sample_data

Quick access to sample data from interface

preprocessor: Any
140    @property
141    def preprocessor(self) -> Any:
142        """Quick access to preprocessor from interface"""
143
144        if hasattr(self.interface, "preprocessor"):
145            return self.interface.preprocessor
146
147        if hasattr(self.interface, "tokenizer"):
148            if self.interface.tokenizer is not None:
149                return self.interface.tokenizer
150
151        if hasattr(self.interface, "feature_extractor"):
152            if self.interface.feature_extractor is not None:
153                return self.interface.feature_extractor
154
155        return None

Quick access to preprocessor from interface

onnx_model: Optional[opsml.types.model.OnnxModel]
157    @property
158    def onnx_model(self) -> Optional[OnnxModel]:
159        """Quick access to onnx model from interface"""
160        return self.interface.onnx_model

Quick access to onnx model from interface

model_metadata: opsml.types.model.ModelMetadata
162    @property
163    def model_metadata(self) -> ModelMetadata:
164        """Loads `ModelMetadata` class"""
165
166        from opsml.storage.card_loader import ModelCardLoader
167
168        return ModelCardLoader(self).load_model_metadata()

Loads ModelMetadata class

card_type: str
170    @property
171    def card_type(self) -> str:
172        return CardType.MODELCARD.value
model_fields = {'name': FieldInfo(annotation=str, required=False, default='undefined'), 'repository': FieldInfo(annotation=str, required=False, default='undefined'), 'contact': FieldInfo(annotation=str, required=False, default='undefined'), 'version': FieldInfo(annotation=str, required=False, default='0.0.0'), 'uid': FieldInfo(annotation=Union[str, NoneType], required=False), 'info': FieldInfo(annotation=Union[CardInfo, NoneType], required=False), 'tags': FieldInfo(annotation=Dict[str, str], required=False, default={}), 'interface': FieldInfo(annotation=ModelInterface, required=True, metadata=[SerializeAsAny()]), 'datacard_uid': FieldInfo(annotation=Union[str, NoneType], required=False), 'to_onnx': FieldInfo(annotation=bool, required=False, default=False), 'metadata': FieldInfo(annotation=ModelCardMetadata, required=False, default=ModelCardMetadata(interface_type='', description=Description(summary=None, sample_code=None, Notes=None), data_schema=DataSchema(data_type=None, input_features=None, output_features=None, onnx_input_features=None, onnx_output_features=None, onnx_data_type=None, onnx_version=None), runcard_uid=None, pipelinecard_uid=None, auditcard_uid=None))}
model_computed_fields = {}
Inherited Members
pydantic.main.BaseModel
BaseModel
model_extra
model_fields_set
model_construct
model_copy
model_dump
model_dump_json
model_json_schema
model_parametrized_name
model_post_init
model_rebuild
model_validate
model_validate_json
model_validate_strings
dict
json
parse_obj
parse_raw
parse_file
from_orm
construct
copy
schema
schema_json
validate
update_forward_refs
opsml.cards.base.ArtifactCard
name
repository
contact
version
uid
info
tags
validate_args
add_tag
uri
artifact_uri