truefoundry 0.3.2__py3-none-any.whl → 0.4.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of truefoundry might be problematic. Click here for more details.

Files changed (225) hide show
  1. truefoundry/cli/__main__.py +3 -17
  2. truefoundry/common/__init__.py +0 -0
  3. truefoundry/common/request_utils.py +56 -0
  4. truefoundry/deploy/auto_gen/models.py +29 -1
  5. truefoundry/deploy/cli/cli.py +1 -1
  6. truefoundry/deploy/lib/auth/credential_provider.py +2 -12
  7. truefoundry/deploy/lib/clients/servicefoundry_client.py +0 -9
  8. truefoundry/deploy/lib/exceptions.py +1 -6
  9. truefoundry/deploy/lib/session.py +1 -16
  10. truefoundry/{python_deploy_codegen.py → deploy/python_deploy_codegen.py} +1 -0
  11. truefoundry/langchain/truefoundry_chat.py +1 -1
  12. truefoundry/langchain/truefoundry_embeddings.py +1 -1
  13. truefoundry/langchain/truefoundry_llm.py +1 -1
  14. truefoundry/langchain/utils.py +0 -41
  15. truefoundry/ml/__init__.py +46 -6
  16. truefoundry/ml/artifact/__init__.py +0 -0
  17. truefoundry/ml/artifact/truefoundry_artifact_repo.py +1120 -0
  18. truefoundry/ml/autogen/__init__.py +0 -0
  19. truefoundry/ml/autogen/client/__init__.py +373 -0
  20. truefoundry/ml/autogen/client/api/__init__.py +16 -0
  21. truefoundry/ml/autogen/client/api/auth_api.py +184 -0
  22. truefoundry/ml/autogen/client/api/deprecated_api.py +605 -0
  23. truefoundry/ml/autogen/client/api/experiments_api.py +2109 -0
  24. truefoundry/ml/autogen/client/api/health_api.py +299 -0
  25. truefoundry/ml/autogen/client/api/metrics_api.py +371 -0
  26. truefoundry/ml/autogen/client/api/mlfoundry_artifacts_api.py +7213 -0
  27. truefoundry/ml/autogen/client/api/python_deployment_config_api.py +201 -0
  28. truefoundry/ml/autogen/client/api/run_artifacts_api.py +231 -0
  29. truefoundry/ml/autogen/client/api/runs_api.py +2919 -0
  30. truefoundry/ml/autogen/client/api_client.py +822 -0
  31. truefoundry/ml/autogen/client/api_response.py +30 -0
  32. truefoundry/ml/autogen/client/configuration.py +489 -0
  33. truefoundry/ml/autogen/client/exceptions.py +161 -0
  34. truefoundry/ml/autogen/client/models/__init__.py +344 -0
  35. truefoundry/ml/autogen/client/models/add_custom_metrics_to_model_version_request_dto.py +69 -0
  36. truefoundry/ml/autogen/client/models/add_features_to_model_version_request_dto.py +83 -0
  37. truefoundry/ml/autogen/client/models/agent.py +125 -0
  38. truefoundry/ml/autogen/client/models/agent_app.py +118 -0
  39. truefoundry/ml/autogen/client/models/agent_open_api_tool.py +143 -0
  40. truefoundry/ml/autogen/client/models/agent_open_api_tool_with_fqn.py +144 -0
  41. truefoundry/ml/autogen/client/models/agent_with_fqn.py +127 -0
  42. truefoundry/ml/autogen/client/models/artifact_dto.py +115 -0
  43. truefoundry/ml/autogen/client/models/artifact_response_dto.py +75 -0
  44. truefoundry/ml/autogen/client/models/artifact_type.py +39 -0
  45. truefoundry/ml/autogen/client/models/artifact_version_dto.py +141 -0
  46. truefoundry/ml/autogen/client/models/artifact_version_response_dto.py +77 -0
  47. truefoundry/ml/autogen/client/models/artifact_version_status.py +35 -0
  48. truefoundry/ml/autogen/client/models/assistant_message.py +89 -0
  49. truefoundry/ml/autogen/client/models/authorize_user_for_model_request_dto.py +69 -0
  50. truefoundry/ml/autogen/client/models/authorize_user_for_model_version_request_dto.py +69 -0
  51. truefoundry/ml/autogen/client/models/backfill_default_storage_integration_id_request_dto.py +67 -0
  52. truefoundry/ml/autogen/client/models/blob_storage_reference.py +93 -0
  53. truefoundry/ml/autogen/client/models/body_get_search_runs_get.py +72 -0
  54. truefoundry/ml/autogen/client/models/chat_prompt.py +156 -0
  55. truefoundry/ml/autogen/client/models/chat_prompt_messages_inner.py +171 -0
  56. truefoundry/ml/autogen/client/models/columns_dto.py +73 -0
  57. truefoundry/ml/autogen/client/models/content.py +153 -0
  58. truefoundry/ml/autogen/client/models/content1.py +153 -0
  59. truefoundry/ml/autogen/client/models/content2.py +174 -0
  60. truefoundry/ml/autogen/client/models/content2_any_of_inner.py +150 -0
  61. truefoundry/ml/autogen/client/models/create_artifact_request_dto.py +74 -0
  62. truefoundry/ml/autogen/client/models/create_artifact_response_dto.py +66 -0
  63. truefoundry/ml/autogen/client/models/create_artifact_version_request_dto.py +74 -0
  64. truefoundry/ml/autogen/client/models/create_artifact_version_response_dto.py +66 -0
  65. truefoundry/ml/autogen/client/models/create_dataset_request_dto.py +76 -0
  66. truefoundry/ml/autogen/client/models/create_experiment_request_dto.py +94 -0
  67. truefoundry/ml/autogen/client/models/create_experiment_response_dto.py +67 -0
  68. truefoundry/ml/autogen/client/models/create_model_version_request_dto.py +95 -0
  69. truefoundry/ml/autogen/client/models/create_multi_part_upload_for_dataset_request_dto.py +73 -0
  70. truefoundry/ml/autogen/client/models/create_multi_part_upload_for_dataset_response_dto.py +79 -0
  71. truefoundry/ml/autogen/client/models/create_multi_part_upload_request_dto.py +73 -0
  72. truefoundry/ml/autogen/client/models/create_python_deployment_config_request_dto.py +72 -0
  73. truefoundry/ml/autogen/client/models/create_python_deployment_config_response_dto.py +68 -0
  74. truefoundry/ml/autogen/client/models/create_run_request_dto.py +97 -0
  75. truefoundry/ml/autogen/client/models/create_run_response_dto.py +76 -0
  76. truefoundry/ml/autogen/client/models/dataset_dto.py +112 -0
  77. truefoundry/ml/autogen/client/models/dataset_response_dto.py +75 -0
  78. truefoundry/ml/autogen/client/models/delete_artifact_versions_request_dto.py +65 -0
  79. truefoundry/ml/autogen/client/models/delete_dataset_request_dto.py +74 -0
  80. truefoundry/ml/autogen/client/models/delete_model_version_request_dto.py +65 -0
  81. truefoundry/ml/autogen/client/models/delete_run_request.py +65 -0
  82. truefoundry/ml/autogen/client/models/delete_tag_request_dto.py +68 -0
  83. truefoundry/ml/autogen/client/models/experiment_dto.py +127 -0
  84. truefoundry/ml/autogen/client/models/experiment_id_request_dto.py +67 -0
  85. truefoundry/ml/autogen/client/models/experiment_response_dto.py +75 -0
  86. truefoundry/ml/autogen/client/models/experiment_tag_dto.py +69 -0
  87. truefoundry/ml/autogen/client/models/feature_dto.py +68 -0
  88. truefoundry/ml/autogen/client/models/feature_value_type.py +35 -0
  89. truefoundry/ml/autogen/client/models/file_info_dto.py +76 -0
  90. truefoundry/ml/autogen/client/models/finalize_artifact_version_request_dto.py +101 -0
  91. truefoundry/ml/autogen/client/models/get_experiment_response_dto.py +88 -0
  92. truefoundry/ml/autogen/client/models/get_latest_run_log_response_dto.py +76 -0
  93. truefoundry/ml/autogen/client/models/get_metric_history_response.py +79 -0
  94. truefoundry/ml/autogen/client/models/get_signed_url_for_dataset_write_request_dto.py +68 -0
  95. truefoundry/ml/autogen/client/models/get_signed_urls_for_artifact_version_read_request_dto.py +68 -0
  96. truefoundry/ml/autogen/client/models/get_signed_urls_for_artifact_version_read_response_dto.py +81 -0
  97. truefoundry/ml/autogen/client/models/get_signed_urls_for_artifact_version_write_request_dto.py +69 -0
  98. truefoundry/ml/autogen/client/models/get_signed_urls_for_artifact_version_write_response_dto.py +83 -0
  99. truefoundry/ml/autogen/client/models/get_signed_urls_for_dataset_read_request_dto.py +68 -0
  100. truefoundry/ml/autogen/client/models/get_signed_urls_for_dataset_read_response_dto.py +81 -0
  101. truefoundry/ml/autogen/client/models/get_signed_urls_for_dataset_write_response_dto.py +81 -0
  102. truefoundry/ml/autogen/client/models/get_tenant_id_response_dto.py +74 -0
  103. truefoundry/ml/autogen/client/models/http_validation_error.py +82 -0
  104. truefoundry/ml/autogen/client/models/image_content_part.py +87 -0
  105. truefoundry/ml/autogen/client/models/image_url.py +75 -0
  106. truefoundry/ml/autogen/client/models/internal_metadata.py +180 -0
  107. truefoundry/ml/autogen/client/models/latest_run_log_dto.py +78 -0
  108. truefoundry/ml/autogen/client/models/list_artifact_versions_request_dto.py +107 -0
  109. truefoundry/ml/autogen/client/models/list_artifact_versions_response_dto.py +87 -0
  110. truefoundry/ml/autogen/client/models/list_artifacts_request_dto.py +96 -0
  111. truefoundry/ml/autogen/client/models/list_artifacts_response_dto.py +86 -0
  112. truefoundry/ml/autogen/client/models/list_colums_response_dto.py +75 -0
  113. truefoundry/ml/autogen/client/models/list_datasets_request_dto.py +78 -0
  114. truefoundry/ml/autogen/client/models/list_datasets_response_dto.py +86 -0
  115. truefoundry/ml/autogen/client/models/list_experiments_response_dto.py +86 -0
  116. truefoundry/ml/autogen/client/models/list_files_for_artifact_version_request_dto.py +76 -0
  117. truefoundry/ml/autogen/client/models/list_files_for_artifact_versions_response_dto.py +82 -0
  118. truefoundry/ml/autogen/client/models/list_files_for_dataset_request_dto.py +76 -0
  119. truefoundry/ml/autogen/client/models/list_files_for_dataset_response_dto.py +82 -0
  120. truefoundry/ml/autogen/client/models/list_latest_run_logs_response_dto.py +82 -0
  121. truefoundry/ml/autogen/client/models/list_metric_history_request_dto.py +69 -0
  122. truefoundry/ml/autogen/client/models/list_metric_history_response_dto.py +84 -0
  123. truefoundry/ml/autogen/client/models/list_model_version_response_dto.py +87 -0
  124. truefoundry/ml/autogen/client/models/list_model_versions_request_dto.py +93 -0
  125. truefoundry/ml/autogen/client/models/list_models_request_dto.py +89 -0
  126. truefoundry/ml/autogen/client/models/list_models_response_dto.py +84 -0
  127. truefoundry/ml/autogen/client/models/list_run_artifacts_response_dto.py +84 -0
  128. truefoundry/ml/autogen/client/models/list_run_logs_response_dto.py +82 -0
  129. truefoundry/ml/autogen/client/models/list_seed_experiments_response_dto.py +81 -0
  130. truefoundry/ml/autogen/client/models/log_batch_request_dto.py +106 -0
  131. truefoundry/ml/autogen/client/models/log_metric_request_dto.py +80 -0
  132. truefoundry/ml/autogen/client/models/log_param_request_dto.py +76 -0
  133. truefoundry/ml/autogen/client/models/method.py +37 -0
  134. truefoundry/ml/autogen/client/models/metric_collection_dto.py +82 -0
  135. truefoundry/ml/autogen/client/models/metric_dto.py +76 -0
  136. truefoundry/ml/autogen/client/models/mime_type.py +37 -0
  137. truefoundry/ml/autogen/client/models/model_configuration.py +103 -0
  138. truefoundry/ml/autogen/client/models/model_dto.py +122 -0
  139. truefoundry/ml/autogen/client/models/model_response_dto.py +75 -0
  140. truefoundry/ml/autogen/client/models/model_schema_dto.py +85 -0
  141. truefoundry/ml/autogen/client/models/model_version_dto.py +163 -0
  142. truefoundry/ml/autogen/client/models/model_version_response_dto.py +75 -0
  143. truefoundry/ml/autogen/client/models/multi_part_upload_dto.py +107 -0
  144. truefoundry/ml/autogen/client/models/multi_part_upload_response_dto.py +79 -0
  145. truefoundry/ml/autogen/client/models/multi_part_upload_storage_provider.py +34 -0
  146. truefoundry/ml/autogen/client/models/notify_artifact_version_failure_dto.py +65 -0
  147. truefoundry/ml/autogen/client/models/openapi_spec.py +152 -0
  148. truefoundry/ml/autogen/client/models/param_dto.py +66 -0
  149. truefoundry/ml/autogen/client/models/parameters.py +84 -0
  150. truefoundry/ml/autogen/client/models/prediction_type.py +34 -0
  151. truefoundry/ml/autogen/client/models/resolve_agent_app_response_dto.py +75 -0
  152. truefoundry/ml/autogen/client/models/restore_run_request_dto.py +65 -0
  153. truefoundry/ml/autogen/client/models/run_data_dto.py +104 -0
  154. truefoundry/ml/autogen/client/models/run_dto.py +84 -0
  155. truefoundry/ml/autogen/client/models/run_info_dto.py +105 -0
  156. truefoundry/ml/autogen/client/models/run_log_dto.py +90 -0
  157. truefoundry/ml/autogen/client/models/run_log_input_dto.py +80 -0
  158. truefoundry/ml/autogen/client/models/run_response_dto.py +75 -0
  159. truefoundry/ml/autogen/client/models/run_tag_dto.py +66 -0
  160. truefoundry/ml/autogen/client/models/search_runs_request_dto.py +94 -0
  161. truefoundry/ml/autogen/client/models/search_runs_response_dto.py +84 -0
  162. truefoundry/ml/autogen/client/models/set_experiment_tag_request_dto.py +73 -0
  163. truefoundry/ml/autogen/client/models/set_tag_request_dto.py +76 -0
  164. truefoundry/ml/autogen/client/models/signed_url_dto.py +69 -0
  165. truefoundry/ml/autogen/client/models/stop.py +152 -0
  166. truefoundry/ml/autogen/client/models/store_run_logs_request_dto.py +83 -0
  167. truefoundry/ml/autogen/client/models/system_message.py +89 -0
  168. truefoundry/ml/autogen/client/models/text.py +153 -0
  169. truefoundry/ml/autogen/client/models/text_content_part.py +84 -0
  170. truefoundry/ml/autogen/client/models/update_artifact_version_request_dto.py +74 -0
  171. truefoundry/ml/autogen/client/models/update_dataset_request_dto.py +74 -0
  172. truefoundry/ml/autogen/client/models/update_experiment_request_dto.py +74 -0
  173. truefoundry/ml/autogen/client/models/update_model_version_request_dto.py +93 -0
  174. truefoundry/ml/autogen/client/models/update_run_request_dto.py +78 -0
  175. truefoundry/ml/autogen/client/models/update_run_response_dto.py +76 -0
  176. truefoundry/ml/autogen/client/models/url.py +153 -0
  177. truefoundry/ml/autogen/client/models/user_message.py +89 -0
  178. truefoundry/ml/autogen/client/models/validation_error.py +87 -0
  179. truefoundry/ml/autogen/client/models/validation_error_loc_inner.py +154 -0
  180. truefoundry/ml/autogen/client/rest.py +426 -0
  181. truefoundry/ml/autogen/client_README.md +322 -0
  182. truefoundry/ml/cli/__init__.py +0 -0
  183. truefoundry/ml/cli/cli.py +18 -0
  184. truefoundry/ml/cli/commands/__init__.py +3 -0
  185. truefoundry/ml/cli/commands/download.py +87 -0
  186. truefoundry/ml/constants.py +84 -0
  187. truefoundry/ml/enums.py +70 -0
  188. truefoundry/ml/env_vars.py +13 -0
  189. truefoundry/ml/exceptions.py +8 -0
  190. truefoundry/ml/git_info.py +60 -0
  191. truefoundry/ml/internal_namespace.py +52 -0
  192. truefoundry/ml/log_types/__init__.py +4 -0
  193. truefoundry/ml/log_types/artifacts/artifact.py +427 -0
  194. truefoundry/ml/log_types/artifacts/constants.py +33 -0
  195. truefoundry/ml/log_types/artifacts/dataset.py +383 -0
  196. truefoundry/ml/log_types/artifacts/general_artifact.py +110 -0
  197. truefoundry/ml/log_types/artifacts/model.py +628 -0
  198. truefoundry/ml/log_types/artifacts/model_extras.py +48 -0
  199. truefoundry/ml/log_types/artifacts/utils.py +161 -0
  200. truefoundry/ml/log_types/image/__init__.py +3 -0
  201. truefoundry/ml/log_types/image/constants.py +8 -0
  202. truefoundry/ml/log_types/image/image.py +358 -0
  203. truefoundry/ml/log_types/image/image_normalizer.py +101 -0
  204. truefoundry/ml/log_types/image/types.py +68 -0
  205. truefoundry/ml/log_types/plot.py +281 -0
  206. truefoundry/ml/log_types/pydantic_base.py +10 -0
  207. truefoundry/ml/log_types/utils.py +12 -0
  208. truefoundry/ml/logger.py +17 -0
  209. truefoundry/ml/login.py +241 -0
  210. truefoundry/ml/mlfoundry_api.py +1620 -0
  211. truefoundry/ml/mlfoundry_run.py +1238 -0
  212. truefoundry/ml/run_utils.py +102 -0
  213. truefoundry/ml/services/__init__.py +0 -0
  214. truefoundry/ml/services/auth_service.py +109 -0
  215. truefoundry/ml/services/entities.py +108 -0
  216. truefoundry/ml/services/servicefoundry_service.py +35 -0
  217. truefoundry/ml/services/utils.py +122 -0
  218. truefoundry/ml/session.py +271 -0
  219. truefoundry/ml/validation_utils.py +346 -0
  220. truefoundry/pydantic_v1.py +5 -1
  221. {truefoundry-0.3.2.dist-info → truefoundry-0.4.0.dev0.dist-info}/METADATA +19 -12
  222. truefoundry-0.4.0.dev0.dist-info/RECORD +342 -0
  223. truefoundry-0.3.2.dist-info/RECORD +0 -136
  224. {truefoundry-0.3.2.dist-info → truefoundry-0.4.0.dev0.dist-info}/WHEEL +0 -0
  225. {truefoundry-0.3.2.dist-info → truefoundry-0.4.0.dev0.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,628 @@
1
+ import copy
2
+ import datetime
3
+ import json
4
+ import logging
5
+ import os.path
6
+ import tempfile
7
+ import uuid
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union
10
+
11
+ from truefoundry.ml.artifact.truefoundry_artifact_repo import (
12
+ ArtifactIdentifier,
13
+ MlFoundryArtifactsRepository,
14
+ )
15
+ from truefoundry.ml.autogen.client import ( # type: ignore[attr-defined]
16
+ AddCustomMetricsToModelVersionRequestDto,
17
+ ArtifactType,
18
+ CreateArtifactVersionRequestDto,
19
+ CreateModelVersionRequestDto,
20
+ DeleteArtifactVersionsRequestDto,
21
+ FinalizeArtifactVersionRequestDto,
22
+ MetricDto,
23
+ MlfoundryArtifactsApi,
24
+ ModelDto,
25
+ ModelVersionDto,
26
+ NotifyArtifactVersionFailureDto,
27
+ UpdateModelVersionRequestDto,
28
+ )
29
+ from truefoundry.ml.autogen.client import ( # type: ignore[attr-defined]
30
+ InternalMetadata as InternalMetadataDto,
31
+ )
32
+ from truefoundry.ml.enums import ModelFramework
33
+ from truefoundry.ml.exceptions import MlFoundryException
34
+ from truefoundry.ml.log_types.artifacts.constants import (
35
+ FILES_DIR,
36
+ INTERNAL_METADATA_PATH,
37
+ MODEL_DIR_NAME,
38
+ MODEL_SCHEMA_UPDATE_FAILURE_HELP,
39
+ )
40
+ from truefoundry.ml.log_types.artifacts.model_extras import CustomMetric, ModelSchema
41
+ from truefoundry.ml.log_types.artifacts.utils import (
42
+ _copy_additional_files,
43
+ _validate_artifact_metadata,
44
+ _validate_description,
45
+ )
46
+ from truefoundry.ml.session import _get_api_client
47
+ from truefoundry.pydantic_v1 import BaseModel, Extra
48
+ from truefoundry.version import __version__
49
+
50
+ if TYPE_CHECKING:
51
+ from truefoundry.ml.mlfoundry_run import MlFoundryRun
52
+
53
+ logger = logging.getLogger("truefoundry.ml")
54
+
55
+
56
+ # TODO: Add some progress indicators for upload and download
57
+ # TODO: Support async download and upload
58
+
59
+
60
+ class ModelVersionInternalMetadata(BaseModel):
61
+ class Config:
62
+ extra = Extra.allow
63
+
64
+ files_dir: str # relative to root
65
+ model_dir: str # relative to `files_dir`
66
+ model_is_null: bool = False
67
+ framework: ModelFramework = ModelFramework.UNKNOWN
68
+ transformers_pipeline_task: Optional[str] = None
69
+ model_filename: Optional[str] = None
70
+ mlfoundry_version: Optional[str] = None
71
+ truefoundry_version: Optional[str] = None
72
+
73
+ def dict(self, *args, **kwargs):
74
+ dct = super().dict(*args, **kwargs)
75
+ dct["framework"] = dct["framework"].value
76
+ return dct
77
+
78
+
79
+ class ModelVersionDownloadInfo(BaseModel):
80
+ download_dir: str
81
+ model_dir: str
82
+ model_framework: ModelFramework = ModelFramework.UNKNOWN
83
+ model_filename: Optional[str] = None
84
+
85
+
86
+ class ModelVersion:
87
+ def __init__(
88
+ self,
89
+ model_version: ModelVersionDto,
90
+ model: ModelDto,
91
+ ) -> None:
92
+ self._api_client = _get_api_client()
93
+ self._mlfoundry_artifacts_api = MlfoundryArtifactsApi(
94
+ api_client=self._api_client
95
+ )
96
+ self._model_version = model_version
97
+ self._model = model
98
+ self._deleted = False
99
+ self._description: str = ""
100
+ self._metadata: Dict[str, Any] = {}
101
+ self._model_schema: Optional[ModelSchema] = None
102
+ self._metrics: List[MetricDto] = []
103
+ self._set_metrics_attr()
104
+ self._set_mutable_attrs()
105
+
106
+ @classmethod
107
+ def from_fqn(cls, fqn: str) -> "ModelVersion":
108
+ """
109
+ Get the version of a model to download contents or load them in memory
110
+
111
+ Args:
112
+ fqn (str): Fully qualified name of the model version.
113
+
114
+ Returns:
115
+ ModelVersion: An ModelVersion instance of the Model
116
+
117
+ Examples:
118
+
119
+ ```python
120
+ from truefoundry.ml import get_client, ModelVersion
121
+
122
+ client = get_client()
123
+ model_version = ModelVersion.from_fqn(fqn="<your-model-fqn>")
124
+ ```
125
+ """
126
+ api_client = _get_api_client()
127
+ mlfoundry_artifacts_api = MlfoundryArtifactsApi(api_client=api_client)
128
+ _model_version = mlfoundry_artifacts_api.get_model_version_by_fqn_get(fqn=fqn)
129
+ model_version = _model_version.model_version
130
+ _model = mlfoundry_artifacts_api.get_model_get(id=model_version.model_id)
131
+ model = _model.model
132
+ instance = cls(model_version=model_version, model=model)
133
+ return instance
134
+
135
+ def _ensure_not_deleted(self):
136
+ if self._deleted:
137
+ raise MlFoundryException(
138
+ "Model Version was deleted, cannot perform updates on a deleted version"
139
+ )
140
+
141
+ def _set_metrics_attr(self):
142
+ self._metrics = sorted(
143
+ self._model_version.metrics or [], key=lambda m: m.timestamp
144
+ )
145
+
146
+ def _set_mutable_attrs(self):
147
+ self._description = self._model_version.description or ""
148
+ self._metadata = copy.deepcopy(self._model_version.artifact_metadata)
149
+ self._model_schema = copy.deepcopy(self._model_version.model_schema)
150
+
151
+ def _refetch_model_version(self):
152
+ self._model_version = (
153
+ self._mlfoundry_artifacts_api.get_artifact_version_by_id_get(
154
+ id=self._model_version.id
155
+ )
156
+ )
157
+ self._set_metrics_attr()
158
+ self._set_mutable_attrs()
159
+
160
+ def __repr__(self):
161
+ return f"{self.__class__.__name__}(fqn={self.fqn!r}, model_schema={self._model_schema!r})"
162
+
163
+ def _get_artifacts_repo(self):
164
+ return MlFoundryArtifactsRepository(
165
+ artifact_identifier=ArtifactIdentifier(
166
+ artifact_version_id=uuid.UUID(self._model_version.id)
167
+ ),
168
+ api_client=self._api_client,
169
+ )
170
+
171
+ @property
172
+ def name(self) -> str:
173
+ """Get the name of the model"""
174
+ return self._model.name
175
+
176
+ @property
177
+ def model_fqn(self) -> str:
178
+ """Get fqn of the model"""
179
+ return self._model.fqn
180
+
181
+ @property
182
+ def version(self) -> int:
183
+ """Get version information of the model"""
184
+ return self._model_version.version
185
+
186
+ @property
187
+ def fqn(self) -> str:
188
+ """Get fqn of the current model version"""
189
+ return self._model_version.fqn
190
+
191
+ @property
192
+ def step(self) -> int:
193
+ """Get the step in which model was created"""
194
+ return self._model_version.step
195
+
196
+ @property
197
+ def description(self) -> Optional[str]:
198
+ """Get description of the model"""
199
+ return self._description
200
+
201
+ @description.setter
202
+ def description(self, value: str):
203
+ """set the description of the model"""
204
+ _validate_description(value)
205
+ self._description = value
206
+
207
+ @property
208
+ def metadata(self) -> Dict[str, Any]:
209
+ """Get metadata for the current model"""
210
+ return self._metadata
211
+
212
+ @metadata.setter
213
+ def metadata(self, value: Dict[str, Any]):
214
+ """set the metadata for current model"""
215
+ _validate_artifact_metadata(value)
216
+ self._metadata = value
217
+
218
+ @property
219
+ def model_schema(self) -> Optional[ModelSchema]:
220
+ """get the model schema for current model"""
221
+ return self._model_schema
222
+
223
+ @model_schema.setter
224
+ def model_schema(self, value: Union[Dict[str, Any], ModelSchema]):
225
+ if not isinstance(value, ModelSchema):
226
+ value = ModelSchema.parse_obj(value)
227
+ self._model_schema = value
228
+
229
+ @property
230
+ def metrics(self) -> Dict[str, Union[float, int]]:
231
+ """get the metrics for the current version of the model"""
232
+ metrics_as_kv: Dict[str, Union[float, int]] = {}
233
+ for metric in self._metrics:
234
+ metrics_as_kv[metric.key] = metric.value
235
+ return metrics_as_kv
236
+
237
+ @property
238
+ def created_by(self) -> str:
239
+ """Get the information about who created the model version"""
240
+ return self._model_version.created_by
241
+
242
+ @property
243
+ def created_at(self) -> datetime.datetime:
244
+ """Get the time at which model version was created"""
245
+ return self._model_version.created_at
246
+
247
+ @property
248
+ def updated_at(self) -> datetime.datetime:
249
+ """Get the information about when the model version was updated"""
250
+ return self._model_version.updated_at
251
+
252
+ def raw_download(
253
+ self,
254
+ path: Optional[Union[str, Path]],
255
+ overwrite: bool = False,
256
+ progress: Optional[bool] = None,
257
+ ) -> str:
258
+ """
259
+ Download a model file or directory to a local directory if applicable, and return a
260
+ local path for it.
261
+
262
+ Args:
263
+ path (str): Absolute path of the local filesystem destination directory to which to
264
+ download the specified models. This directory must already exist.
265
+ If unspecified, the models will either be downloaded to a new
266
+ uniquely-named directory on the local filesystem.
267
+ overwrite (bool): If True it will overwrite the file if it is already present in the download directory else
268
+ it will throw an error
269
+ progress (bool): value to show progress bar, defaults to None.
270
+
271
+ Returns:
272
+ path: Absolute path of the local filesystem location containing the desired models.
273
+
274
+ Examples:
275
+
276
+ ```python
277
+ from truefoundry.ml import get_client
278
+
279
+ client = get_client()
280
+ model_version = client.get_model_version_by_fqn(fqn="<your-model-fqn>")
281
+ model_version.raw_download(path="<your-desired-download-path>")
282
+ ```
283
+ """
284
+ logger.info("Downloading model version contents, this might take a while ...")
285
+ artifacts_repo = self._get_artifacts_repo()
286
+ return artifacts_repo.download_artifacts(
287
+ artifact_path="", dst_path=path, overwrite=overwrite, progress=progress
288
+ )
289
+
290
+ def _download(
291
+ self,
292
+ path: Optional[Union[str, Path]],
293
+ overwrite: bool = False,
294
+ progress: Optional[bool] = None,
295
+ ) -> Tuple[ModelVersionInternalMetadata, ModelVersionDownloadInfo]:
296
+ self._ensure_not_deleted()
297
+ download_dir = self.raw_download(
298
+ path=path, overwrite=overwrite, progress=progress
299
+ )
300
+ internal_metadata_path = os.path.join(download_dir, INTERNAL_METADATA_PATH)
301
+ if not os.path.exists(internal_metadata_path):
302
+ raise MlFoundryException(
303
+ "Model version seems to be corrupted or in invalid format due to missing model metadata. "
304
+ "You can still use .raw_download(path='/your/path/here') to download and inspect files."
305
+ )
306
+ with open(internal_metadata_path) as f:
307
+ internal_metadata = ModelVersionInternalMetadata.parse_obj(json.load(f))
308
+ download_info = ModelVersionDownloadInfo(
309
+ download_dir=os.path.join(download_dir, internal_metadata.files_dir),
310
+ model_dir=os.path.join(
311
+ download_dir, internal_metadata.files_dir, internal_metadata.model_dir
312
+ ),
313
+ model_framework=internal_metadata.framework,
314
+ model_filename=internal_metadata.model_filename,
315
+ )
316
+ return internal_metadata, download_info
317
+
318
+ def download(
319
+ self,
320
+ path: Optional[Union[str, Path]],
321
+ overwrite: bool = False,
322
+ progress: Optional[bool] = None,
323
+ ) -> ModelVersionDownloadInfo:
324
+ """
325
+ Download a model file or directory to a local directory if applicable, and return download info
326
+ containing `model_dir` - local path where model was downloaded
327
+
328
+ Args:
329
+ path (str): Absolute path of the local filesystem destination directory to which to
330
+ download the specified models. This directory must already exist.
331
+ If unspecified, the models will either be downloaded to a new
332
+ uniquely-named directory on the local filesystem.
333
+ overwrite (bool): If True it will overwrite the file if it is already present in the download directory else
334
+ it will throw an error
335
+ progress (bool): value to show progress bar, defaults to None.
336
+
337
+ Returns:
338
+ ModelVersionDownloadInfo: Download Info instance containing
339
+ `model_dir` (path to downloaded model folder) and other metadata
340
+
341
+ Examples:
342
+
343
+ ```python
344
+ from truefoundry.ml import get_client
345
+
346
+ client = get_client()
347
+ model_version = client.get_model_version_by_fqn(fqn="<your-model-fqn>")
348
+ download_info = model_version.download(path="<your-desired-download-path>")
349
+ print(download_info.model_dir)
350
+ ```
351
+ """
352
+ _, download_info = self._download(
353
+ path=path, overwrite=overwrite, progress=progress
354
+ )
355
+ return download_info
356
+
357
+ def delete(self) -> bool:
358
+ """
359
+ Deletes the current instance of the ModelVersion hence deleting the current version.
360
+
361
+ Returns:
362
+ True if model was deleted successfully
363
+
364
+ Examples:
365
+
366
+ ```python
367
+ from truefoundry.ml import get_client
368
+
369
+ client = get_client()
370
+ model_version = client.get_model_version_by_fqn(fqn="<your-model-fqn>")
371
+ model_version.delete()
372
+ ```
373
+ """
374
+ self._ensure_not_deleted()
375
+ self._mlfoundry_artifacts_api.delete_artifact_version_post(
376
+ delete_artifact_versions_request_dto=DeleteArtifactVersionsRequestDto(
377
+ id=self._model_version.id
378
+ )
379
+ )
380
+ self._deleted = True
381
+ return True
382
+
383
+ def update(self):
384
+ """
385
+ Updates the current instance of the ModelVersion hence updating the current version.
386
+
387
+ Examples:
388
+
389
+ ```python
390
+ from truefoundry.ml import get_client
391
+
392
+ client = get_client()
393
+ model_version = client.get_model_version_by_fqn(fqn="<your-model-fqn>")
394
+ model_version.description = 'This is the new description'
395
+ model_version.update()
396
+ ```
397
+ """
398
+ self._ensure_not_deleted()
399
+ kwargs = {}
400
+ if self.model_schema is not None:
401
+ kwargs["model_schema"] = self.model_schema
402
+ _model_version = self._mlfoundry_artifacts_api.update_model_version_post(
403
+ update_model_version_request_dto=UpdateModelVersionRequestDto(
404
+ id=self._model_version.id,
405
+ description=self.description,
406
+ artifact_metadata=self.metadata,
407
+ **kwargs,
408
+ )
409
+ )
410
+ self._model_version = _model_version.model_version
411
+ self._set_metrics_attr()
412
+ self._set_mutable_attrs()
413
+
414
+
415
+ def calculate_model_size(artifact_dir: tempfile.TemporaryDirectory):
416
+ """
417
+ Tells about the size of the model
418
+
419
+ Args:
420
+ artifact_dir (str): directory in which model is present.
421
+
422
+ Returns:
423
+ total size of the model
424
+ """
425
+ total_size = 0
426
+ for path, _dirs, files in os.walk(artifact_dir.name):
427
+ for f in files:
428
+ file_path = os.path.join(path, f)
429
+ total_size += os.stat(file_path).st_size
430
+ return total_size
431
+
432
+
433
+ def _log_model_version( # noqa: C901
434
+ run: Optional["MlFoundryRun"],
435
+ name: str,
436
+ model_file_or_folder: str,
437
+ framework: Optional[Union[ModelFramework, str]],
438
+ mlfoundry_artifacts_api: Optional[MlfoundryArtifactsApi] = None,
439
+ ml_repo_id: Optional[str] = None,
440
+ additional_files: Sequence[Tuple[Union[str, Path], Optional[str]]] = (),
441
+ description: Optional[str] = None,
442
+ metadata: Optional[Dict[str, Any]] = None,
443
+ model_schema: Optional[Union[Dict[str, Any], ModelSchema]] = None,
444
+ custom_metrics: Optional[List[Union[CustomMetric, Dict[str, Any]]]] = None,
445
+ step: Optional[int] = 0,
446
+ progress: Optional[bool] = None,
447
+ ) -> ModelVersion:
448
+ if (run and mlfoundry_artifacts_api) or (not run and not mlfoundry_artifacts_api):
449
+ raise MlFoundryException(
450
+ "Exactly one of run, mlfoundry_artifacts_api should be passed"
451
+ )
452
+ if mlfoundry_artifacts_api and not ml_repo_id:
453
+ raise MlFoundryException(
454
+ "If mlfoundry_artifacts_api is passed, ml_repo_id must also be passed"
455
+ )
456
+ if run:
457
+ mlfoundry_artifacts_api = run._mlfoundry_artifacts_api
458
+
459
+ assert mlfoundry_artifacts_api is not None
460
+
461
+ custom_metrics = custom_metrics or []
462
+ metadata = metadata or {}
463
+ additional_files = additional_files or {}
464
+ step = step or 0
465
+
466
+ # validations
467
+ if framework is None:
468
+ framework = ModelFramework.UNKNOWN
469
+ elif not isinstance(framework, ModelFramework):
470
+ framework = ModelFramework(framework)
471
+
472
+ _validate_description(description)
473
+ _validate_artifact_metadata(metadata)
474
+
475
+ if model_schema is not None and not isinstance(model_schema, ModelSchema):
476
+ model_schema = ModelSchema.parse_obj(model_schema)
477
+
478
+ if custom_metrics and not model_schema:
479
+ raise MlFoundryException(
480
+ "Custom Metrics defined without adding the Model Schema"
481
+ )
482
+ custom_metrics = [
483
+ CustomMetric.parse_obj(cm) if not isinstance(cm, CustomMetric) else cm
484
+ for cm in custom_metrics
485
+ ]
486
+
487
+ logger.info("Logging model and additional files, this might take a while ...")
488
+ temp_dir = tempfile.TemporaryDirectory(prefix="truefoundry-")
489
+
490
+ internal_metadata = ModelVersionInternalMetadata(
491
+ framework=framework,
492
+ files_dir=FILES_DIR,
493
+ model_dir=MODEL_DIR_NAME,
494
+ model_filename=(
495
+ os.path.basename(model_file_or_folder)
496
+ if model_file_or_folder and os.path.isfile(model_file_or_folder)
497
+ else None
498
+ ),
499
+ mlfoundry_version=__version__,
500
+ truefoundry_version=__version__,
501
+ )
502
+
503
+ try:
504
+ local_files_dir = os.path.join(temp_dir.name, internal_metadata.files_dir)
505
+ os.makedirs(local_files_dir, exist_ok=True)
506
+ # in case model was None, we still create an empty dir
507
+ local_model_dir = os.path.join(local_files_dir, internal_metadata.model_dir)
508
+ os.makedirs(local_model_dir, exist_ok=True)
509
+
510
+ logger.info("Adding model file/folder to model version content")
511
+ model_file_or_folder = [
512
+ (model_file_or_folder, MODEL_DIR_NAME.rstrip(os.sep) + os.sep)
513
+ ]
514
+ _copy_additional_files(
515
+ root_dir=temp_dir.name,
516
+ files_dir=internal_metadata.files_dir,
517
+ model_dir=internal_metadata.model_dir,
518
+ additional_files=model_file_or_folder,
519
+ ignore_model_dir_dest_conflict=True,
520
+ )
521
+
522
+ # verify additional files and paths, copy additional files
523
+ if additional_files:
524
+ logger.info("Adding `additional_files` to model version contents")
525
+ _copy_additional_files(
526
+ root_dir=temp_dir.name,
527
+ files_dir=internal_metadata.files_dir,
528
+ model_dir=internal_metadata.model_dir,
529
+ additional_files=additional_files,
530
+ ignore_model_dir_dest_conflict=False,
531
+ )
532
+
533
+ except Exception as e:
534
+ temp_dir.cleanup()
535
+ raise MlFoundryException("Failed to log model") from e
536
+
537
+ # save internal metadata
538
+ local_internal_metadata_path = os.path.join(temp_dir.name, INTERNAL_METADATA_PATH)
539
+ os.makedirs(os.path.dirname(local_internal_metadata_path), exist_ok=True)
540
+ with open(local_internal_metadata_path, "w") as f:
541
+ json.dump(internal_metadata.dict(), f)
542
+
543
+ # create entry
544
+ _create_artifact_version_response = (
545
+ mlfoundry_artifacts_api.create_artifact_version_post(
546
+ create_artifact_version_request_dto=CreateArtifactVersionRequestDto(
547
+ experiment_id=int(run._experiment_id if run else ml_repo_id),
548
+ artifact_type=ArtifactType.MODEL,
549
+ name=name,
550
+ )
551
+ )
552
+ )
553
+ version_id = _create_artifact_version_response.id
554
+ artifacts_repo = MlFoundryArtifactsRepository(
555
+ artifact_identifier=ArtifactIdentifier(artifact_version_id=version_id),
556
+ api_client=mlfoundry_artifacts_api.api_client,
557
+ )
558
+ model_size = calculate_model_size(temp_dir)
559
+ try:
560
+ logger.info(
561
+ "Packaging and uploading files to remote with Total Size: %.6f MB",
562
+ model_size / 1000000.0,
563
+ )
564
+ artifacts_repo.log_artifacts(
565
+ local_dir=temp_dir.name, artifact_path=None, progress=progress
566
+ )
567
+ except Exception as e:
568
+ mlfoundry_artifacts_api.notify_failure_post(
569
+ notify_artifact_version_failure_dto=NotifyArtifactVersionFailureDto(
570
+ id=version_id
571
+ )
572
+ )
573
+ raise MlFoundryException("Failed to log model") from e
574
+ finally:
575
+ temp_dir.cleanup()
576
+
577
+ # Note: Here we call from_dict instead of directly passing in init and relying on it
578
+ # to convert because the complicated union of types generates a custom type to handle casting
579
+ # Check the source of `InternalMetadataDto` to see the generated code
580
+ internal_metadata_dto = InternalMetadataDto.from_dict(
581
+ internal_metadata.dict() if internal_metadata is not None else {}
582
+ )
583
+ mlfoundry_artifacts_api.finalize_artifact_version_post(
584
+ finalize_artifact_version_request_dto=FinalizeArtifactVersionRequestDto(
585
+ id=version_id,
586
+ run_uuid=run.run_id if run else None,
587
+ artifact_size=model_size,
588
+ internal_metadata=internal_metadata_dto,
589
+ step=step if run else None,
590
+ )
591
+ )
592
+ _model_version = mlfoundry_artifacts_api.create_model_version_post(
593
+ create_model_version_request_dto=CreateModelVersionRequestDto(
594
+ artifact_version_id=version_id,
595
+ description=description,
596
+ artifact_metadata=metadata,
597
+ internal_metadata=internal_metadata_dto,
598
+ data_path=INTERNAL_METADATA_PATH,
599
+ step=step if run else None,
600
+ )
601
+ )
602
+ model_version = _model_version.model_version
603
+
604
+ # update model schema at end
605
+ update_args = {
606
+ "id": version_id,
607
+ "model_framework": framework.value,
608
+ }
609
+ if model_schema:
610
+ update_args["model_schema"] = model_schema
611
+
612
+ try:
613
+ _model_version = mlfoundry_artifacts_api.update_model_version_post(
614
+ update_model_version_request_dto=UpdateModelVersionRequestDto(**update_args)
615
+ )
616
+ model_version = _model_version.model_version
617
+ if model_schema:
618
+ _model_version = mlfoundry_artifacts_api.add_custom_metrics_to_model_version_post(
619
+ add_custom_metrics_to_model_version_request_dto=AddCustomMetricsToModelVersionRequestDto(
620
+ id=version_id, custom_metrics=custom_metrics
621
+ )
622
+ )
623
+ model_version = _model_version.model_version
624
+ except Exception:
625
+ # TODO (chiragjn): what is the best exception to catch here?
626
+ logger.error(MODEL_SCHEMA_UPDATE_FAILURE_HELP.format(fqn=model_version.fqn))
627
+
628
+ return ModelVersion.from_fqn(fqn=model_version.fqn)
@@ -0,0 +1,48 @@
1
+ import enum
2
+ from typing import List, Type, TypeVar
3
+
4
+ from truefoundry.ml.autogen.client import ( # type: ignore[attr-defined]
5
+ ModelSchemaDto,
6
+ )
7
+ from truefoundry.ml.exceptions import MlFoundryException
8
+ from truefoundry.pydantic_v1 import BaseModel
9
+
10
+ T = TypeVar("T")
11
+
12
+
13
+ class BaseEnum(enum.Enum):
14
+ @classmethod
15
+ def values(cls: Type[T]) -> List[T]:
16
+ return [member.value for member in cls]
17
+
18
+ @classmethod
19
+ def _missing_(cls: Type[T], value: object):
20
+ raise MlFoundryException(
21
+ f"Unknown value for type {cls.__name__}: {value}", status_code=400
22
+ )
23
+
24
+
25
+ @enum.unique
26
+ class CustomMetricValueType(str, BaseEnum):
27
+ FLOAT = "float"
28
+
29
+
30
+ @enum.unique
31
+ class CustomMetricType(str, BaseEnum):
32
+ METRIC = "metric"
33
+ PROJECTION = "projection"
34
+
35
+
36
+ class CustomMetric(BaseModel):
37
+ class Config:
38
+ validate_assignment = True
39
+ use_enum_values = True
40
+ extra = "allow"
41
+
42
+ name: str
43
+ value_type: CustomMetricValueType
44
+ type: CustomMetricType
45
+
46
+
47
+ class ModelSchema(ModelSchemaDto):
48
+ pass