zenml-nightly 0.68.1.dev20241102__py3-none-any.whl → 0.68.1.dev20241106__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.
Files changed (42) hide show
  1. zenml/VERSION +1 -1
  2. zenml/artifacts/{load_directory_materializer.py → preexisting_data_materializer.py} +8 -9
  3. zenml/artifacts/utils.py +1 -1
  4. zenml/integrations/__init__.py +3 -1
  5. zenml/integrations/bentoml/materializers/bentoml_bento_materializer.py +19 -31
  6. zenml/integrations/constants.py +1 -0
  7. zenml/integrations/huggingface/materializers/huggingface_datasets_materializer.py +8 -12
  8. zenml/integrations/huggingface/materializers/huggingface_pt_model_materializer.py +17 -18
  9. zenml/integrations/huggingface/materializers/huggingface_t5_materializer.py +2 -5
  10. zenml/integrations/huggingface/materializers/huggingface_tf_model_materializer.py +17 -18
  11. zenml/integrations/huggingface/materializers/huggingface_tokenizer_materializer.py +2 -3
  12. zenml/integrations/langchain/__init__.py +2 -1
  13. zenml/integrations/langchain/materializers/openai_embedding_materializer.py +28 -2
  14. zenml/integrations/lightgbm/materializers/lightgbm_booster_materializer.py +8 -15
  15. zenml/integrations/lightgbm/materializers/lightgbm_dataset_materializer.py +11 -16
  16. zenml/integrations/openai/__init__.py +1 -1
  17. zenml/integrations/openai/hooks/open_ai_failure_hook.py +39 -14
  18. zenml/integrations/pillow/materializers/pillow_image_materializer.py +17 -20
  19. zenml/integrations/polars/materializers/dataframe_materializer.py +26 -39
  20. zenml/integrations/pycaret/materializers/model_materializer.py +7 -22
  21. zenml/integrations/tensorflow/materializers/keras_materializer.py +11 -22
  22. zenml/integrations/tensorflow/materializers/tf_dataset_materializer.py +8 -15
  23. zenml/integrations/vllm/__init__.py +50 -0
  24. zenml/integrations/vllm/flavors/__init__.py +21 -0
  25. zenml/integrations/vllm/flavors/vllm_model_deployer_flavor.py +91 -0
  26. zenml/integrations/vllm/model_deployers/__init__.py +19 -0
  27. zenml/integrations/vllm/model_deployers/vllm_model_deployer.py +263 -0
  28. zenml/integrations/vllm/services/__init__.py +19 -0
  29. zenml/integrations/vllm/services/vllm_deployment.py +197 -0
  30. zenml/integrations/whylogs/materializers/whylogs_materializer.py +11 -18
  31. zenml/integrations/xgboost/materializers/xgboost_booster_materializer.py +11 -22
  32. zenml/integrations/xgboost/materializers/xgboost_dmatrix_materializer.py +10 -19
  33. zenml/materializers/base_materializer.py +68 -1
  34. zenml/orchestrators/step_runner.py +4 -1
  35. zenml/stack/flavor.py +9 -5
  36. zenml/steps/step_context.py +2 -0
  37. zenml/utils/callback_registry.py +71 -0
  38. {zenml_nightly-0.68.1.dev20241102.dist-info → zenml_nightly-0.68.1.dev20241106.dist-info}/METADATA +1 -1
  39. {zenml_nightly-0.68.1.dev20241102.dist-info → zenml_nightly-0.68.1.dev20241106.dist-info}/RECORD +42 -34
  40. {zenml_nightly-0.68.1.dev20241102.dist-info → zenml_nightly-0.68.1.dev20241106.dist-info}/LICENSE +0 -0
  41. {zenml_nightly-0.68.1.dev20241102.dist-info → zenml_nightly-0.68.1.dev20241106.dist-info}/WHEEL +0 -0
  42. {zenml_nightly-0.68.1.dev20241102.dist-info → zenml_nightly-0.68.1.dev20241106.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,263 @@
1
+ # Copyright (c) ZenML GmbH 2024. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at:
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12
+ # or implied. See the License for the specific language governing
13
+ # permissions and limitations under the License.
14
+ """Implementation of the vLLM Model Deployer."""
15
+
16
+ import os
17
+ import shutil
18
+ from typing import ClassVar, Dict, Optional, Type, cast
19
+ from uuid import UUID
20
+
21
+ from zenml.config.global_config import GlobalConfiguration
22
+ from zenml.constants import DEFAULT_SERVICE_START_STOP_TIMEOUT
23
+ from zenml.integrations.vllm.flavors.vllm_model_deployer_flavor import (
24
+ VLLMModelDeployerConfig,
25
+ VLLMModelDeployerFlavor,
26
+ )
27
+ from zenml.integrations.vllm.services.vllm_deployment import (
28
+ VLLMDeploymentService,
29
+ VLLMServiceConfig,
30
+ )
31
+ from zenml.logger import get_logger
32
+ from zenml.model_deployers import BaseModelDeployer, BaseModelDeployerFlavor
33
+ from zenml.services.service import BaseService, ServiceConfig
34
+ from zenml.utils.io_utils import create_dir_recursive_if_not_exists
35
+
36
+ logger = get_logger(__name__)
37
+
38
+
39
+ class VLLMModelDeployer(BaseModelDeployer):
40
+ """vLLM Inference Server."""
41
+
42
+ NAME: ClassVar[str] = "VLLM"
43
+ FLAVOR: ClassVar[Type[BaseModelDeployerFlavor]] = VLLMModelDeployerFlavor
44
+
45
+ _service_path: Optional[str] = None
46
+
47
+ @property
48
+ def config(self) -> VLLMModelDeployerConfig:
49
+ """Returns the `VLLMModelDeployerConfig` config.
50
+
51
+ Returns:
52
+ The configuration.
53
+ """
54
+ return cast(VLLMModelDeployerConfig, self._config)
55
+
56
+ @staticmethod
57
+ def get_service_path(id_: UUID) -> str:
58
+ """Get the path where local vLLM service information is stored.
59
+
60
+ This includes the deployment service configuration, PID and log files
61
+ are stored.
62
+
63
+ Args:
64
+ id_: The ID of the vLLM model deployer.
65
+
66
+ Returns:
67
+ The service path.
68
+ """
69
+ service_path = os.path.join(
70
+ GlobalConfiguration().local_stores_path,
71
+ str(id_),
72
+ )
73
+ create_dir_recursive_if_not_exists(service_path)
74
+ return service_path
75
+
76
+ @property
77
+ def local_path(self) -> str:
78
+ """Returns the path to the root directory.
79
+
80
+ This is where all configurations for vLLM deployment daemon processes
81
+ are stored.
82
+
83
+ If the service path is not set in the config by the user, the path is
84
+ set to a local default path according to the component ID.
85
+
86
+ Returns:
87
+ The path to the local service root directory.
88
+ """
89
+ if self._service_path is not None:
90
+ return self._service_path
91
+
92
+ if self.config.service_path:
93
+ self._service_path = self.config.service_path
94
+ else:
95
+ self._service_path = self.get_service_path(self.id)
96
+
97
+ create_dir_recursive_if_not_exists(self._service_path)
98
+ return self._service_path
99
+
100
+ @staticmethod
101
+ def get_model_server_info( # type: ignore[override]
102
+ service_instance: "VLLMDeploymentService",
103
+ ) -> Dict[str, Optional[str]]:
104
+ """Return implementation specific information on the model server.
105
+
106
+ Args:
107
+ service_instance: vLLM deployment service object
108
+
109
+ Returns:
110
+ A dictionary containing the model server information.
111
+ """
112
+ return {
113
+ "HEALTH_CHECK_URL": service_instance.get_healthcheck_url(),
114
+ "PREDICTION_URL": service_instance.get_prediction_url(),
115
+ "SERVICE_PATH": service_instance.status.runtime_path,
116
+ "DAEMON_PID": str(service_instance.status.pid),
117
+ }
118
+
119
+ def perform_deploy_model(
120
+ self,
121
+ id: UUID,
122
+ config: ServiceConfig,
123
+ timeout: int = DEFAULT_SERVICE_START_STOP_TIMEOUT,
124
+ ) -> BaseService:
125
+ """Create a new vLLM deployment service or update an existing one.
126
+
127
+ This should serve the supplied model and deployment configuration.
128
+
129
+ This method has two modes of operation, depending on the `replace`
130
+ argument value:
131
+
132
+ * if `replace` is False, calling this method will create a new vLLM
133
+ deployment server to reflect the model and other configuration
134
+ parameters specified in the supplied vLLM service `config`.
135
+
136
+ * if `replace` is True, this method will first attempt to find an
137
+ existing vLLM deployment service that is *equivalent* to the
138
+ supplied configuration parameters. Two or more vLLM deployment
139
+ services are considered equivalent if they have the same
140
+ `pipeline_name`, `pipeline_step_name` and `model_name` configuration
141
+ parameters. To put it differently, two vLLM deployment services
142
+ are equivalent if they serve versions of the same model deployed by
143
+ the same pipeline step. If an equivalent vLLM deployment is found,
144
+ it will be updated in place to reflect the new configuration
145
+ parameters.
146
+
147
+ Callers should set `replace` to True if they want a continuous model
148
+ deployment workflow that doesn't spin up a new vLLM deployment
149
+ server for each new model version. If multiple equivalent vLLM
150
+ deployment servers are found, one is selected at random to be updated
151
+ and the others are deleted.
152
+
153
+ Args:
154
+ id: the UUID of the vLLM model deployer.
155
+ config: the configuration of the model to be deployed with vLLM.
156
+ timeout: the timeout in seconds to wait for the vLLM server
157
+ to be provisioned and successfully started or updated. If set
158
+ to 0, the method will return immediately after the vLLM
159
+ server is provisioned, without waiting for it to fully start.
160
+
161
+ Returns:
162
+ The ZenML vLLM deployment service object that can be used to
163
+ interact with the vLLM model http server.
164
+ """
165
+ config = cast(VLLMServiceConfig, config)
166
+ service = self._create_new_service(
167
+ id=id, timeout=timeout, config=config
168
+ )
169
+ logger.info(f"Created a new vLLM deployment service: {service}")
170
+ return service
171
+
172
+ def _clean_up_existing_service(
173
+ self,
174
+ timeout: int,
175
+ force: bool,
176
+ existing_service: VLLMDeploymentService,
177
+ ) -> None:
178
+ # stop the older service
179
+ existing_service.stop(timeout=timeout, force=force)
180
+
181
+ # delete the old configuration file
182
+ if existing_service.status.runtime_path:
183
+ shutil.rmtree(existing_service.status.runtime_path)
184
+
185
+ # the step will receive a config from the user that mentions the number
186
+ # of workers etc.the step implementation will create a new config using
187
+ # all values from the user and add values like pipeline name, model_uri
188
+ def _create_new_service(
189
+ self, id: UUID, timeout: int, config: VLLMServiceConfig
190
+ ) -> VLLMDeploymentService:
191
+ """Creates a new VLLMDeploymentService.
192
+
193
+ Args:
194
+ id: the ID of the vLLM deployment service to be created or updated.
195
+ timeout: the timeout in seconds to wait for the vLLM server
196
+ to be provisioned and successfully started or updated.
197
+ config: the configuration of the model to be deployed with vLLM.
198
+
199
+ Returns:
200
+ The VLLMDeploymentService object that can be used to interact
201
+ with the vLLM model server.
202
+ """
203
+ # set the root runtime path with the stack component's UUID
204
+ config.root_runtime_path = self.local_path
205
+ # create a new service for the new model
206
+ service = VLLMDeploymentService(uuid=id, config=config)
207
+ service.start(timeout=timeout)
208
+
209
+ return service
210
+
211
+ def perform_stop_model(
212
+ self,
213
+ service: BaseService,
214
+ timeout: int = DEFAULT_SERVICE_START_STOP_TIMEOUT,
215
+ force: bool = False,
216
+ ) -> BaseService:
217
+ """Method to stop a model server.
218
+
219
+ Args:
220
+ service: The service to stop.
221
+ timeout: Timeout in seconds to wait for the service to stop.
222
+ force: If True, force the service to stop.
223
+
224
+ Returns:
225
+ The stopped service.
226
+ """
227
+ service.stop(timeout=timeout, force=force)
228
+ return service
229
+
230
+ def perform_start_model(
231
+ self,
232
+ service: BaseService,
233
+ timeout: int = DEFAULT_SERVICE_START_STOP_TIMEOUT,
234
+ ) -> BaseService:
235
+ """Method to start a model server.
236
+
237
+ Args:
238
+ service: The service to start.
239
+ timeout: Timeout in seconds to wait for the service to start.
240
+
241
+ Returns:
242
+ The started service.
243
+ """
244
+ service.start(timeout=timeout)
245
+ return service
246
+
247
+ def perform_delete_model(
248
+ self,
249
+ service: BaseService,
250
+ timeout: int = DEFAULT_SERVICE_START_STOP_TIMEOUT,
251
+ force: bool = False,
252
+ ) -> None:
253
+ """Method to delete all configuration of a model server.
254
+
255
+ Args:
256
+ service: The service to delete.
257
+ timeout: Timeout in seconds to wait for the service to stop.
258
+ force: If True, force the service to stop.
259
+ """
260
+ service = cast(VLLMDeploymentService, service)
261
+ self._clean_up_existing_service(
262
+ existing_service=service, timeout=timeout, force=force
263
+ )
@@ -0,0 +1,19 @@
1
+ # Copyright (c) ZenML GmbH 2024. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at:
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12
+ # or implied. See the License for the specific language governing
13
+ # permissions and limitations under the License.
14
+ """Initialization of the vLLM Inference Server."""
15
+
16
+ from zenml.integrations.vllm.services.vllm_deployment import ( # noqa
17
+ VLLMDeploymentService,
18
+ VLLMServiceConfig,
19
+ )
@@ -0,0 +1,197 @@
1
+ # Copyright (c) ZenML GmbH 2024. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at:
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12
+ # or implied. See the License for the specific language governing
13
+ # permissions and limitations under the License.
14
+ """Implementation of the vLLM Inference Server Service."""
15
+
16
+ import os
17
+ from typing import Any, List, Optional, Union
18
+
19
+ from zenml.constants import DEFAULT_LOCAL_SERVICE_IP_ADDRESS
20
+ from zenml.logger import get_logger
21
+ from zenml.services import (
22
+ HTTPEndpointHealthMonitor,
23
+ HTTPEndpointHealthMonitorConfig,
24
+ LocalDaemonService,
25
+ LocalDaemonServiceConfig,
26
+ LocalDaemonServiceEndpoint,
27
+ LocalDaemonServiceEndpointConfig,
28
+ ServiceEndpointProtocol,
29
+ ServiceType,
30
+ )
31
+ from zenml.services.service import BaseDeploymentService
32
+
33
+ logger = get_logger(__name__)
34
+
35
+
36
+ VLLM_PREDICTION_URL_PATH = "v1"
37
+ VLLM_HEALTHCHECK_URL_PATH = "health"
38
+
39
+
40
+ class VLLMDeploymentEndpointConfig(LocalDaemonServiceEndpointConfig):
41
+ """vLLM deployment service configuration.
42
+
43
+ Attributes:
44
+ prediction_url_path: URI subpath for prediction requests
45
+ """
46
+
47
+ prediction_url_path: str
48
+
49
+
50
+ class VLLMDeploymentEndpoint(LocalDaemonServiceEndpoint):
51
+ """A service endpoint exposed by the vLLM deployment daemon.
52
+
53
+ Attributes:
54
+ config: service endpoint configuration
55
+ """
56
+
57
+ config: VLLMDeploymentEndpointConfig
58
+ monitor: HTTPEndpointHealthMonitor
59
+
60
+ @property
61
+ def prediction_url(self) -> Optional[str]:
62
+ """Gets the prediction URL for the endpoint.
63
+
64
+ Returns:
65
+ the prediction URL for the endpoint
66
+ """
67
+ uri = self.status.uri
68
+ if not uri:
69
+ return None
70
+ return os.path.join(uri, self.config.prediction_url_path)
71
+
72
+
73
+ class VLLMServiceConfig(LocalDaemonServiceConfig):
74
+ """vLLM service configurations."""
75
+
76
+ model: str
77
+ port: int
78
+ host: Optional[str] = None
79
+ blocking: bool = True
80
+ # If unspecified, model name or path will be used.
81
+ tokenizer: Optional[str] = None
82
+ served_model_name: Optional[Union[str, List[str]]] = None
83
+ # Trust remote code from huggingface.
84
+ trust_remote_code: Optional[bool] = False
85
+ # ['auto', 'slow', 'mistral']
86
+ tokenizer_mode: Optional[str] = "auto"
87
+ # ['auto', 'half', 'float16', 'bfloat16', 'float', 'float32']
88
+ dtype: Optional[str] = "auto"
89
+ # The specific model version to use. It can be a branch name, a tag name, or a commit id.
90
+ # If unspecified, will use the default version.
91
+ revision: Optional[str] = None
92
+
93
+
94
+ class VLLMDeploymentService(LocalDaemonService, BaseDeploymentService):
95
+ """vLLM Inference Server Deployment Service."""
96
+
97
+ SERVICE_TYPE = ServiceType(
98
+ name="vllm-deployment",
99
+ type="model-serving",
100
+ flavor="vllm",
101
+ description="vLLM Inference prediction service",
102
+ )
103
+ config: VLLMServiceConfig
104
+ endpoint: VLLMDeploymentEndpoint
105
+
106
+ def __init__(self, config: VLLMServiceConfig, **attrs: Any):
107
+ """Initialize the vLLM deployment service.
108
+
109
+ Args:
110
+ config: service configuration
111
+ attrs: additional attributes to set on the service
112
+ """
113
+ if isinstance(config, VLLMServiceConfig) and "endpoint" not in attrs:
114
+ endpoint = VLLMDeploymentEndpoint(
115
+ config=VLLMDeploymentEndpointConfig(
116
+ protocol=ServiceEndpointProtocol.HTTP,
117
+ port=config.port,
118
+ ip_address=config.host or DEFAULT_LOCAL_SERVICE_IP_ADDRESS,
119
+ prediction_url_path=VLLM_PREDICTION_URL_PATH,
120
+ ),
121
+ monitor=HTTPEndpointHealthMonitor(
122
+ config=HTTPEndpointHealthMonitorConfig(
123
+ healthcheck_uri_path=VLLM_HEALTHCHECK_URL_PATH,
124
+ )
125
+ ),
126
+ )
127
+ attrs["endpoint"] = endpoint
128
+ super().__init__(config=config, **attrs)
129
+
130
+ def run(self) -> None:
131
+ """Start the service."""
132
+ logger.info(
133
+ "Starting vLLM inference server service as blocking "
134
+ "process... press CTRL+C once to stop it."
135
+ )
136
+
137
+ self.endpoint.prepare_for_start()
138
+
139
+ import uvloop
140
+ from vllm.entrypoints.openai.api_server import run_server
141
+ from vllm.entrypoints.openai.cli_args import make_arg_parser
142
+ from vllm.utils import FlexibleArgumentParser
143
+
144
+ try:
145
+ parser = make_arg_parser(FlexibleArgumentParser())
146
+ args = parser.parse_args()
147
+ # Override port with the available port
148
+ self.config.port = self.endpoint.status.port
149
+ # Update the arguments in place
150
+ args.__dict__.update(self.config.model_dump())
151
+ uvloop.run(run_server(args=args))
152
+ except KeyboardInterrupt:
153
+ logger.info("Stopping vLLM prediction service...")
154
+
155
+ @property
156
+ def prediction_url(self) -> Optional[str]:
157
+ """Gets the prediction URL for the endpoint.
158
+
159
+ Returns:
160
+ the prediction URL for the endpoint
161
+ """
162
+ if not self.is_running:
163
+ return None
164
+ return self.endpoint.prediction_url_path
165
+
166
+ def predict(self, data: "Any") -> "Any":
167
+ """Make a prediction using the service.
168
+
169
+ Args:
170
+ data: data to make a prediction on
171
+
172
+ Returns:
173
+ The prediction result.
174
+
175
+ Raises:
176
+ Exception: if the service is not running
177
+ ValueError: if the prediction endpoint is unknown.
178
+ """
179
+ if not self.is_running:
180
+ raise Exception(
181
+ "vLLM Inference service is not running. "
182
+ "Please start the service before making predictions."
183
+ )
184
+ if self.endpoint.prediction_url is not None:
185
+ from openai import OpenAI
186
+
187
+ client = OpenAI(
188
+ api_key="EMPTY",
189
+ base_url=self.endpoint.prediction_url,
190
+ )
191
+ models = client.models.list()
192
+ model = models.data[0].id
193
+ result = client.completions.create(model=model, prompt=data)
194
+ # TODO: We can add support for client.chat.completions.create
195
+ else:
196
+ raise ValueError("No endpoint known for prediction.")
197
+ return result
@@ -14,7 +14,6 @@
14
14
  """Implementation of the whylogs materializer."""
15
15
 
16
16
  import os
17
- import tempfile
18
17
  from typing import Any, ClassVar, Dict, Tuple, Type, cast
19
18
 
20
19
  from whylogs.core import DatasetProfileView # type: ignore
@@ -51,18 +50,14 @@ class WhylogsMaterializer(BaseMaterializer):
51
50
  """
52
51
  filepath = os.path.join(self.uri, PROFILE_FILENAME)
53
52
 
54
- # Create a temporary folder
55
- temp_dir = tempfile.mkdtemp(prefix="zenml-temp-")
56
- temp_file = os.path.join(str(temp_dir), PROFILE_FILENAME)
53
+ with self.get_temporary_directory(delete_at_exit=True) as temp_dir:
54
+ temp_file = os.path.join(str(temp_dir), PROFILE_FILENAME)
57
55
 
58
- # Copy from artifact store to temporary file
59
- fileio.copy(filepath, temp_file)
60
- profile_view = DatasetProfileView.read(temp_file)
56
+ # Copy from artifact store to temporary file
57
+ fileio.copy(filepath, temp_file)
58
+ profile_view = DatasetProfileView.read(temp_file)
61
59
 
62
- # Cleanup and return
63
- fileio.rmtree(temp_dir)
64
-
65
- return profile_view
60
+ return profile_view
66
61
 
67
62
  def save(self, profile_view: DatasetProfileView) -> None:
68
63
  """Writes a whylogs dataset profile view.
@@ -72,15 +67,13 @@ class WhylogsMaterializer(BaseMaterializer):
72
67
  """
73
68
  filepath = os.path.join(self.uri, PROFILE_FILENAME)
74
69
 
75
- # Create a temporary folder
76
- temp_dir = tempfile.mkdtemp(prefix="zenml-temp-")
77
- temp_file = os.path.join(str(temp_dir), PROFILE_FILENAME)
70
+ with self.get_temporary_directory(delete_at_exit=True) as temp_dir:
71
+ temp_file = os.path.join(str(temp_dir), PROFILE_FILENAME)
78
72
 
79
- profile_view.write(temp_file)
73
+ profile_view.write(temp_file)
80
74
 
81
- # Copy it into artifact store
82
- fileio.copy(temp_file, filepath)
83
- fileio.rmtree(temp_dir)
75
+ # Copy it into artifact store
76
+ fileio.copy(temp_file, filepath)
84
77
 
85
78
  try:
86
79
  self._upload_to_whylabs(profile_view)
@@ -14,7 +14,6 @@
14
14
  """Implementation of an XGBoost booster materializer."""
15
15
 
16
16
  import os
17
- import tempfile
18
17
  from typing import Any, ClassVar, Tuple, Type
19
18
 
20
19
  import xgboost as xgb
@@ -43,18 +42,15 @@ class XgboostBoosterMaterializer(BaseMaterializer):
43
42
  """
44
43
  filepath = os.path.join(self.uri, DEFAULT_FILENAME)
45
44
 
46
- # Create a temporary folder
47
- temp_dir = tempfile.mkdtemp(prefix="zenml-temp-")
48
- temp_file = os.path.join(str(temp_dir), DEFAULT_FILENAME)
45
+ with self.get_temporary_directory(delete_at_exit=True) as temp_dir:
46
+ temp_file = os.path.join(str(temp_dir), DEFAULT_FILENAME)
49
47
 
50
- # Copy from artifact store to temporary file
51
- fileio.copy(filepath, temp_file)
52
- booster = xgb.Booster()
53
- booster.load_model(temp_file)
48
+ # Copy from artifact store to temporary file
49
+ fileio.copy(filepath, temp_file)
50
+ booster = xgb.Booster()
51
+ booster.load_model(temp_file)
54
52
 
55
- # Cleanup and return
56
- fileio.rmtree(temp_dir)
57
- return booster
53
+ return booster
58
54
 
59
55
  def save(self, booster: xgb.Booster) -> None:
60
56
  """Creates a JSON serialization for a xgboost Booster model.
@@ -64,14 +60,7 @@ class XgboostBoosterMaterializer(BaseMaterializer):
64
60
  """
65
61
  filepath = os.path.join(self.uri, DEFAULT_FILENAME)
66
62
 
67
- # Make a temporary phantom artifact
68
- with tempfile.NamedTemporaryFile(
69
- mode="w", suffix=".json", delete=False
70
- ) as f:
71
- booster.save_model(f.name)
72
- # Copy it into artifact store
73
- fileio.copy(f.name, filepath)
74
-
75
- # Close and remove the temporary file
76
- f.close()
77
- fileio.remove(f.name)
63
+ with self.get_temporary_directory(delete_at_exit=True) as temp_dir:
64
+ temp_file = os.path.join(str(temp_dir), DEFAULT_FILENAME)
65
+ booster.save_model(temp_file)
66
+ fileio.copy(temp_file, filepath)
@@ -14,7 +14,6 @@
14
14
  """Implementation of the XGBoost dmatrix materializer."""
15
15
 
16
16
  import os
17
- import tempfile
18
17
  from typing import TYPE_CHECKING, Any, ClassVar, Dict, Tuple, Type
19
18
 
20
19
  import xgboost as xgb
@@ -46,17 +45,14 @@ class XgboostDMatrixMaterializer(BaseMaterializer):
46
45
  """
47
46
  filepath = os.path.join(self.uri, DEFAULT_FILENAME)
48
47
 
49
- # Create a temporary folder
50
- temp_dir = tempfile.mkdtemp(prefix="zenml-temp-")
51
- temp_file = os.path.join(str(temp_dir), DEFAULT_FILENAME)
48
+ with self.get_temporary_directory(delete_at_exit=True) as temp_dir:
49
+ temp_file = os.path.join(str(temp_dir), DEFAULT_FILENAME)
52
50
 
53
- # Copy from artifact store to temporary file
54
- fileio.copy(filepath, temp_file)
55
- matrix = xgb.DMatrix(temp_file)
51
+ # Copy from artifact store to temporary file
52
+ fileio.copy(filepath, temp_file)
53
+ matrix = xgb.DMatrix(temp_file)
56
54
 
57
- # Cleanup and return
58
- fileio.rmtree(temp_dir)
59
- return matrix
55
+ return matrix
60
56
 
61
57
  def save(self, matrix: xgb.DMatrix) -> None:
62
58
  """Creates a binary serialization for a xgboost.DMatrix object.
@@ -66,15 +62,10 @@ class XgboostDMatrixMaterializer(BaseMaterializer):
66
62
  """
67
63
  filepath = os.path.join(self.uri, DEFAULT_FILENAME)
68
64
 
69
- # Make a temporary phantom artifact
70
- with tempfile.NamedTemporaryFile(mode="wb", delete=False) as f:
71
- matrix.save_binary(f.name)
72
- # Copy it into artifact store
73
- fileio.copy(f.name, filepath)
74
-
75
- # Close and remove the temporary file
76
- f.close()
77
- fileio.remove(f.name)
65
+ with self.get_temporary_directory(delete_at_exit=True) as temp_dir:
66
+ temp_file = os.path.join(str(temp_dir), DEFAULT_FILENAME)
67
+ matrix.save_binary(temp_file)
68
+ fileio.copy(temp_file, filepath)
78
69
 
79
70
  def extract_metadata(
80
71
  self, dataset: xgb.DMatrix