This file is a merged representation of the entire codebase, combining all repository files into a single document. Generated by Repomix on: 2025-02-06T16:56:07.786Z ================================================================ File Summary ================================================================ Purpose: -------- This file contains a packed representation of the entire repository's contents. It is designed to be easily consumable by AI systems for analysis, code review, or other automated processes. File Format: ------------ The content is organized as follows: 1. This summary section 2. Repository information 3. Directory structure 4. Multiple file entries, each consisting of: a. A separator line (================) b. The file path (File: path/to/file) c. Another separator line d. The full contents of the file e. A blank line Usage Guidelines: ----------------- - This file should be treated as read-only. Any changes should be made to the original repository files, not this packed version. - When processing this file, use the file path to distinguish between different files in the repository. - Be aware that this file may contain sensitive information. Handle it with the same level of security as you would the original repository. Notes: ------ - Some files may have been excluded based on .gitignore rules and Repomix's configuration. - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files. Additional Info: ---------------- ================================================================ Directory Structure ================================================================ docs/ book/ component-guide/ alerters/ alerters.md custom.md discord.md slack.md annotators/ annotators.md argilla.md custom.md label-studio.md pigeon.md prodigy.md artifact-stores/ artifact-stores.md azure.md custom.md gcp.md local.md s3.md container-registries/ aws.md azure.md container-registries.md custom.md default.md dockerhub.md gcp.md github.md data-validators/ custom.md data-validators.md deepchecks.md evidently.md great-expectations.md whylogs.md experiment-trackers/ comet.md custom.md experiment-trackers.md mlflow.md neptune.md vertexai.md wandb.md feature-stores/ custom.md feast.md feature-stores.md image-builders/ aws.md custom.md gcp.md image-builders.md kaniko.md local.md model-deployers/ bentoml.md custom.md databricks.md huggingface.md mlflow.md model-deployers.md seldon.md vllm.md model-registries/ custom.md mlflow.md model-registries.md orchestrators/ airflow.md azureml.md custom.md databricks.md hyperai.md kubeflow.md kubernetes.md lightning.md local-docker.md local.md orchestrators.md sagemaker.md skypilot-vm.md tekton.md vertex.md step-operators/ azureml.md custom.md kubernetes.md modal.md sagemaker.md spark-kubernetes.md step-operators.md vertex.md component-guide.md integration-overview.md README.md ================================================================ Files ================================================================ ================ File: docs/book/component-guide/alerters/alerters.md ================ --- description: Sending automated alerts to chat services. icon: message-exclamation --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Alerters **Alerters** allow you to send messages to chat services (like Slack, Discord, Mattermost, etc.) from within your pipelines. This is useful to immediately get notified when failures happen, for general monitoring/reporting, and also for building human-in-the-loop ML. ## Alerter Flavors Currently, the [SlackAlerter](slack.md) and [DiscordAlerter](discord.md) are the available alerter integrations. However, it is straightforward to extend ZenML and [build an alerter for other chat services](custom.md). | Alerter | Flavor | Integration | Notes | |------------------------------------|-----------|-------------|--------------------------------------------------------------------| | [Slack](slack.md) | `slack` | `slack` | Interacts with a Slack channel | | [Discord](discord.md) | `discord` | `discord` | Interacts with a Discord channel | | [Custom Implementation](custom.md) | _custom_ | | Extend the alerter abstraction and provide your own implementation | {% hint style="info" %} If you would like to see the available flavors of alerters in your terminal, you can use the following command: ```shell zenml alerter flavor list ``` {% endhint %} ## How to use Alerters with ZenML Each alerter integration comes with specific standard steps that you can use out of the box. However, you first need to register an alerter component in your terminal: ```shell zenml alerter register ... ``` Then you can add it to your stack using ```shell zenml stack register ... -al ``` Afterward, you can import the alerter standard steps provided by the respective integration and directly use them in your pipelines.
ZenML Scarf
================ File: docs/book/component-guide/alerters/custom.md ================ --- description: Learning how to develop a custom alerter. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a Custom Alerter {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} ### Base Abstraction The base abstraction for alerters is very basic, as it only defines two abstract methods that subclasses should implement: * `post()` takes a string, posts it to the desired chat service, and returns `True` if the operation succeeded, else `False`. * `ask()` does the same as `post()`, but after sending the message, it waits until someone approves or rejects the operation from within the chat service (e.g., by sending "approve" / "reject" to the bot as a response). `ask()` then only returns `True` if the operation succeeded and was approved, else `False`. Then base abstraction looks something like this: ```python class BaseAlerter(StackComponent, ABC): """Base class for all ZenML alerters.""" def post( self, message: str, params: Optional[BaseAlerterStepParameters] ) -> bool: """Post a message to a chat service.""" return True def ask( self, question: str, params: Optional[BaseAlerterStepParameters] ) -> bool: """Post a message to a chat service and wait for approval.""" return True ``` {% hint style="info" %} This is a slimmed-down version of the base implementation. To see the full docstrings and imports, please check [the source code on GitHub](https://github.com/zenml-io/zenml/blob/main/src/zenml/alerter/base\_alerter.py). {% endhint %} ### Building your own custom alerter Creating your own custom alerter can be done in three steps: 1. Create a class that inherits from the `BaseAlerter` and implement the `post()` and `ask()` methods. ```python from typing import Optional from zenml.alerter import BaseAlerter, BaseAlerterStepParameters class MyAlerter(BaseAlerter): """My alerter class.""" def post( self, message: str, config: Optional[BaseAlerterStepParameters] ) -> bool: """Post a message to a chat service.""" ... return "Hey, I implemented an alerter." def ask( self, question: str, config: Optional[BaseAlerterStepParameters] ) -> bool: """Post a message to a chat service and wait for approval.""" ... return True ``` 2. If you need to configure your custom alerter, you can also implement a config object. ```python from zenml.alerter.base_alerter import BaseAlerterConfig class MyAlerterConfig(BaseAlerterConfig): my_param: str ``` 3. Finally, you can bring the implementation and the configuration together in a new flavor object. ```python from typing import Type, TYPE_CHECKING from zenml.alerter import BaseAlerterFlavor if TYPE_CHECKING: from zenml.stack import StackComponent, StackComponentConfig class MyAlerterFlavor(BaseAlerterFlavor): @property def name(self) -> str: return "my_alerter" @property def config_class(self) -> Type[StackComponentConfig]: from my_alerter_config import MyAlerterConfig return MyAlerterConfig @property def implementation_class(self) -> Type[StackComponent]: from my_alerter import MyAlerter return MyAlerter ``` Once you are done with the implementation, you can register your new flavor through the CLI. Please ensure you **point to the flavor class via dot notation**: ```shell zenml alerter flavor register ``` For example, if your flavor class `MyAlerterFlavor` is defined in `flavors/my_flavor.py`, you'd register it by doing: ```shell zenml alerter flavor register flavors.my_flavor.MyAlerterFlavor ``` {% hint style="warning" %} ZenML resolves the flavor class by taking the path where you initialized zenml (via `zenml init`) as the starting point of resolution. Therefore, please ensure you follow [the best practice](../../how-to/project-setup-and-management/setting-up-a-project-repository/set-up-repository.md) of initializing zenml at the root of your repository. If ZenML does not find an initialized ZenML repository in any parent directory, it will default to the current working directory, but usually, it's better to not have to rely on this mechanism and initialize zenml at the root. {% endhint %} Afterward, you should see the new custom alerter flavor in the list of available alerter flavors: ```shell zenml alerter flavor list ``` {% hint style="warning" %} It is important to draw attention to when and how these abstractions are coming into play in a ZenML workflow. * The **MyAlerterFlavor** class is imported and utilized upon the creation of the custom flavor through the CLI. * The **MyAlerterConfig** class is imported when someone tries to register/update a stack component with the `my_alerter` flavor. Especially, during the registration process of the stack component, the config will be used to validate the values given by the user. As `Config` objects are inherently `pydantic` objects, you can also add your own custom validators here. * The **MyAlerter** only comes into play when the component is ultimately in use. The design behind this interaction lets us separate the configuration of the flavor from its implementation. This way we can register flavors and components even when the major dependencies behind their implementation are not installed in our local setting (assuming the `MyAlerterFlavor` and the `MyAlerterConfig` are implemented in a different module/path than the actual `MyAlerter`). {% endhint %}
ZenML Scarf
================ File: docs/book/component-guide/alerters/discord.md ================ --- description: Sending automated alerts to a Discord channel. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Discord Alerter The `DiscordAlerter` enables you to send messages to a dedicated Discord channel directly from within your ZenML pipelines. The `discord` integration contains the following two standard steps: * [discord\_alerter\_post\_step](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-discord/#zenml.integrations.discord.steps.discord\_alerter\_post\_step.discord\_alerter\_post\_step) takes a string message, posts it to a Discord channel, and returns whether the operation was successful. * [discord\_alerter\_ask\_step](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-discord/#zenml.integrations.discord.steps.discord\_alerter\_ask\_step.discord\_alerter\_ask\_step) also posts a message to a Discord channel, but waits for user feedback, and only returns `True` if a user explicitly approved the operation from within Discord (e.g., by sending "approve" / "reject" to the bot in response). Interacting with Discord from within your pipelines can be very useful in practice: * The `discord_alerter_post_step` allows you to get notified immediately when failures happen (e.g., model performance degradation, data drift, ...), * The `discord_alerter_ask_step` allows you to integrate a human-in-the-loop into your pipelines before executing critical steps, such as deploying new models. ## How to use it ### Requirements Before you can use the `DiscordAlerter`, you first need to install ZenML's `discord` integration: ```shell zenml integration install discord -y ``` {% hint style="info" %} See the [Integrations](../README.md) page for more details on ZenML integrations and how to install and use them. {% endhint %} ### Setting Up a Discord Bot In order to use the `DiscordAlerter`, you first need to have a Discord workspace set up with a channel that you want your pipelines to post to. This is the `` you will need when registering the discord alerter component. Then, you need to [create a Discord App with a bot in your server](https://discordpy.readthedocs.io/en/latest/discord.html) . {% hint style="info" %} Note in the bot token copy step, if you don't find the copy button then click on reset token to reset the bot and you will get a new token which you can use. Also, make sure you give necessary permissions to the bot required for sending and receiving messages. {% endhint %} ### Registering a Discord Alerter in ZenML Next, you need to register a `discord` alerter in ZenML and link it to the bot you just created. You can do this with the following command: ```shell zenml alerter register discord_alerter \ --flavor=discord \ --discord_token= \ --default_discord_channel_id= ``` After you have registered the `discord_alerter`, you can add it to your stack like this: ```shell zenml stack register ... -al discord_alerter ``` Here is where you can find the required parameters: #### DISCORD_CHANNEL_ID Open the discord server, then right-click on the text channel and click on the 'Copy Channel ID' option. {% hint style="info" %} If you don't see any 'Copy Channel ID' option for your channel, go to "User Settings" > "Advanced" and make sure "Developer Mode" is active. {% endhint %} #### DISCORD_TOKEN This is the Discord token of your bot. You can find the instructions on how to set up a bot, invite it to your channel, and find its token [here](https://discordpy.readthedocs.io/en/latest/discord.html). {% hint style="warning" %} When inviting the bot to your channel, make sure it has at least the following permissions: * Read Messages/View Channels * Send Messages * Send Messages in Threads {% endhint %} ### How to Use the Discord Alerter After you have a `DiscordAlerter` configured in your stack, you can directly import the [discord\_alerter\_post\_step](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-discord/#zenml.integrations.discord.steps.discord\_alerter\_post\_step.discord\_alerter\_post\_step) and [discord\_alerter\_ask\_step](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-discord/#zenml.integrations.discord.steps.discord\_alerter\_ask\_step.discord\_alerter\_ask\_step) steps and use them in your pipelines. Since these steps expect a string message as input (which needs to be the output of another step), you typically also need to define a dedicated formatter step that takes whatever data you want to communicate and generates the string message that the alerter should post. As an example, adding `discord_alerter_ask_step()` to your pipeline could look like this: ```python from zenml.integrations.discord.steps.discord_alerter_ask_step import discord_alerter_ask_step from zenml import step, pipeline @step def my_formatter_step(artifact_to_be_communicated) -> str: return f"Here is my artifact {artifact_to_be_communicated}!" @pipeline def my_pipeline(...): ... artifact_to_be_communicated = ... message = my_formatter_step(artifact_to_be_communicated) approved = discord_alerter_ask_step(message) ... # Potentially have different behavior in subsequent steps if `approved` if __name__ == "__main__": my_pipeline() ``` For more information and a full list of configurable attributes of the Discord alerter, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-discord/#zenml.integrations.discord.alerters.discord\_alerter.DiscordAlerter) .
ZenML Scarf
================ File: docs/book/component-guide/alerters/slack.md ================ --- description: Sending automated alerts to a Slack channel. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Slack Alerter The `SlackAlerter` enables you to send messages or ask questions within a dedicated Slack channel directly from within your ZenML pipelines and steps. ## How to Create ### Set up a Slack app In order to use the `SlackAlerter`, you first need to have a Slack workspace set up with a channel that you want your pipelines to post to. Then, you need to [create a Slack App](https://api.slack.com/apps?new\_app=1) with a bot in your workspace. Make sure to give it the following permissions in the `OAuth & Permissions` tab under `Scopes`: * `chat:write`, * `channels:read` * `channels:history` ![Slack OAuth Permissions](../../.gitbook/assets/slack-alerter-oauth-permissions.png) In order to be able to use the `ask()` functionality, you need to invite the app to your channel. You can either use the `/invite` command directly in the desired channel or add it through the channel settings: ![Slack OAuth Permissions](../../.gitbook/assets/slack-channel-settings.png) {% hint style="warning" %} It might take some time for your app to register within your workspace and show up in the available list of applications. {% endhint %} ### Registering a Slack Alerter in ZenML To create a `SlackAlerter`, you first need to install ZenML's `slack` integration: ```shell zenml integration install slack -y ``` Once the integration is installed, you can use the ZenML CLI to create a secret and register an alerter linked to the app you just created: ```shell zenml secret create slack_token --oauth_token= zenml alerter register slack_alerter \ --flavor=slack \ --slack_token={{slack_token.oauth_token}} \ --slack_channel_id= ``` Here is where you can find the required parameters: * ``: The channel ID can be found in the channel details. It starts with `C....`. * ``: This is the Slack token of your bot. You can find it in the Slack app settings under `OAuth & Permissions`. ![Slack Token Image](../../.gitbook/assets/slack-alerter-token.png) After you have registered the `slack_alerter`, you can add it to your stack like this: ```shell zenml stack register ... -al slack_alerter --set ``` ## How to Use In ZenML, you can use alerters in various ways. ### Use the `post()` and `ask()` directly You can use the client to fetch the active alerter within your stack and use the `post` and `ask` methods directly: ```python from zenml import pipeline, step from zenml.client import Client @step def post_statement() -> None: Client().active_stack.alerter.post("Step finished!") @step def ask_question() -> bool: return Client().active_stack.alerter.ask("Should I continue?") @pipeline(enable_cache=False) def my_pipeline(): # Step using alerter.post post_statement() # Step using alerter.ask ask_question() if __name__ == "__main__": my_pipeline() ``` {% hint style="warning" %} In case of an error, the output of the `ask()` method default to `False`. {% endhint %} ### Use it with custom settings The Slack alerter comes equipped with a set of options that you can set during runtime: ```python from zenml import pipeline, step from zenml.client import Client # E.g, You can use a different channel ID through the settings. However, if you # want to use the `ask` functionality, make sure that you app is invited to # this channel first. @step(settings={"alerter": {"slack_channel_id": }}) def post_statement() -> None: alerter = Client().active_stack.alerter alerter.post("Posting to another channel!") @pipeline(enable_cache=False) def my_pipeline(): # Using alerter.post post_statement() if __name__ == "__main__": my_pipeline() ``` ## Use it with `SlackAlerterParameters` and `SlackAlerterPayload` You can use these additional classes to further edit your messages: ```python from zenml import pipeline, step, get_step_context from zenml.client import Client from zenml.integrations.slack.alerters.slack_alerter import ( SlackAlerterParameters, SlackAlerterPayload ) # Displaying pipeline info @step def post_statement() -> None: params = SlackAlerterParameters( payload=SlackAlerterPayload( pipeline_name=get_step_context().pipeline.name, step_name=get_step_context().step_run.name, stack_name=Client().active_stack.name, ), ) Client().active_stack.alerter.post( message="This is a message with additional information about your pipeline.", params=params ) # Formatting with blocks @step def ask_question() -> bool: message = ":tada: Should I continue? (Y/N)" my_custom_block = [ { "type": "header", "text": { "type": "plain_text", "text": message, "emoji": True } } ] params = SlackAlerterParameters( blocks=my_custom_block, approve_msg_options=["Y"], disapprove_msg_options=["N"], ) return Client().active_stack.alerter.ask(question=message, params=params) @pipeline(enable_cache=False) def my_pipeline(): post_statement() ask_question() if __name__ == "__main__": my_pipeline() ``` ### Use the predefined steps If you want to only use it in a simple manner, you can also use the steps `slack_alerter_post_step` and `slack_alerter_ask_step`, that are built-in to the Slack integration of ZenML: ```python from zenml import pipeline from zenml.integrations.slack.steps.slack_alerter_post_step import ( slack_alerter_post_step ) from zenml.integrations.slack.steps.slack_alerter_ask_step import ( slack_alerter_ask_step, ) @pipeline(enable_cache=False) def my_pipeline(): slack_alerter_post_step("Posting a statement.") slack_alerter_ask_step("Asking a question. Should I continue?") if __name__ == "__main__": my_pipeline() ``` For more information and a full list of configurable attributes of the Slack alerter, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-slack/#zenml.integrations.slack.alerters.slack\_alerter.SlackAlerter) .
ZenML Scarf
================ File: docs/book/component-guide/annotators/annotators.md ================ --- icon: expand description: Annotating the data in your workflow. --- # Annotators Annotators are a stack component that enables the use of data annotation as part of your ZenML stack and pipelines. You can use the associated CLI command to launch annotation, configure your datasets and get stats on how many labeled tasks you have ready for use. Data annotation/labeling is a core part of MLOps that is frequently left out of the conversation. ZenML will incrementally start to build features that support an iterative annotation workflow that sees the people doing labeling (and their workflows/behaviors) as integrated parts of their ML process(es). ![When and where to annotate.](../../.gitbook/assets/annotation-when-where.png) There are a number of different places in the ML lifecycle where this can happen: * **At the start**: You might be starting out without any data, or with a ton of data but no clear sense of which parts of it are useful to your particular problem. It’s not uncommon to have a lot of data but to be lacking accurate labels for that data. So you can start and get great value from bootstrapping your model: label some data, train your model, and use your model to suggest labels allowing you to speed up your labeling, iterating on and on in this way. Labeling data early on in the process also helps clarify and condense down your specific rules and standards. For example, you might realize that you need to have specific definitions for certain concepts so that your labeling efforts are consistent across your team. * **As new data comes in**: New data will likely continue to come in, and you might want to check in with the labeling process at regular intervals to expose yourself to this new data. (You’ll probably also want to have some kind of automation around detecting data or concept drift, but for certain kinds of unstructured data you probably can never completely abandon the instant feedback of actual contact with the raw data.) * **Samples generated for inference**: Your model will be making predictions on real-world data being passed in. If you store and label this data, you’ll gain a valuable set of data that you can use to compare your labels with what the model was predicting, another possible way to flag drifts of various kinds. This data can then (subject to privacy/user consent) be used in retraining or fine-tuning your model. * **Other ad hoc interventions**: You will probably have some kind of process to identify bad labels, or to find the kinds of examples that your model finds really difficult to make correct predictions. For these, and for areas where you have clear class imbalances, you might want to do ad hoc annotation to supplement the raw materials your model has to learn from. ZenML currently offers standard steps that help you tackle the above use cases, but the stack component and abstraction will continue to be developed to make it easier to use. ### When to use it The annotator is an optional stack component in the ZenML Stack. We designed our abstraction to fit into the larger ML use cases, particularly the training and deployment parts of the lifecycle. The core parts of the annotation workflow include: * using labels or annotations in your training steps in a seamless way * handling the versioning of annotation data * allow for the conversion of annotation data to and from custom formats * handle annotator-specific tasks, for example, the generation of UI config files that Label Studio requires for the web annotation interface ### List of available annotators For production use cases, some more flavors can be found in specific `integrations` modules. In terms of annotators, ZenML features integrations with the following tools. | Annotator | Flavor | Integration | Notes | |-----------------------------------------|----------------|----------------|----------------------------------------------------------------------| | [ArgillaAnnotator](argilla.md) | `argilla` | `argilla` | Connect ZenML with Argilla | | [LabelStudioAnnotator](label-studio.md) | `label_studio` | `label_studio` | Connect ZenML with Label Studio | | [PigeonAnnotator](pigeon.md) | `pigeon` | `pigeon` | Connect ZenML with Pigeon. Notebook only & for image and text classification tasks. | | [ProdigyAnnotator](prodigy.md) | `prodigy` | `prodigy` | Connect ZenML with [Prodigy](https://prodi.gy/) | | [Custom Implementation](custom.md) | _custom_ | | Extend the annotator abstraction and provide your own implementation | If you would like to see the available flavors for annotators, you can use the command: ```shell zenml annotator flavor list ``` ### How to use it The available implementation of the annotator is built on top of the Label Studio integration, which means that using an annotator currently is no different from what's described on the [Label Studio page: How to use it?](label-studio.md#how-do-you-use-it). ([Pigeon](pigeon.md) is also supported, but has a very limited functionality and only works within Jupyter notebooks.) ### A note on names The various annotation tools have mostly standardized around the naming of key concepts as part of how they build their tools. Unfortunately, this hasn't been completely unified so ZenML takes an opinion on which names we use for our stack components and integrations. Key differences to note: * Label Studio refers to the grouping of a set of annotations/tasks as a 'Project', whereas most other tools use the term 'Dataset', so ZenML also calls this grouping a 'Dataset'. * The individual meta-unit for 'an annotation + the source data' is referred to in different ways, but at ZenML (and with Label Studio) we refer to them as 'tasks'. The remaining core concepts ('annotation' and 'prediction', in particular) are broadly used among annotation tools.
ZenML Scarf
================ File: docs/book/component-guide/annotators/argilla.md ================ --- description: Annotating data using Argilla. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Argilla [Argilla](https://github.com/argilla-io/argilla) is a collaboration tool for AI engineers and domain experts who need to build high-quality datasets for their projects. It enables users to build robust language models through faster data curation using both human and machine feedback, providing support for each step in the MLOps cycle, from data labeling to model monitoring. ![Argilla Annotator](../../.gitbook/assets/argilla_annotator.png) Argilla distinguishes itself for its focus on specific use cases and human-in-the-loop approaches. While it does offer programmatic features, Argilla's core value lies in actively involving human experts in the tool-building process, setting it apart from other competitors. ### When would you want to use it? If you need to label textual data as part of your ML workflow, that is the point at which you could consider adding the Argilla annotator stack component as part of your ZenML stack. We currently support the use of annotation at the various stages described in [the main annotators docs page](annotators.md). The Argilla integration currently is built to support annotation using a local (Docker-backed) instance of Argilla as well as a deployed instance of Argilla. There is an easy way to deploy Argilla as a [Hugging Face Space](https://huggingface.co/docs/hub/spaces-sdks-docker-argilla), for instance, which is documented in the [Argilla documentation](https://docs.argilla.io/latest/getting_started/quickstart/). ### How to deploy it? The Argilla Annotator flavor is provided by the Argilla ZenML integration. You need to install it to be able to register it as an Annotator and add it to your stack: ```shell zenml integration install argilla ``` You can either pass the `api_key` directly into the `zenml annotator register` command or you can register it as a secret and pass the secret name into the command. We recommend the latter approach for security reasons. If you want to take the latter approach, be sure to register a secret for whichever artifact store you choose, and then you should make sure to pass the name of that secret into the annotator as the `--authentication_secret`. For example, you'd run: ```shell zenml secret create argilla_secrets --api_key="" ``` (Visit the Argilla documentation and interface to obtain your API key.) Then register your annotator with ZenML: ```shell zenml annotator register argilla --flavor argilla --authentication_secret=argilla_secrets --port=6900 ``` When using a deployed instance of Argilla, the instance URL must be specified without any trailing `/` at the end. If you are using a Hugging Face Spaces instance and its visibility is set to private, you must also set the `headers` parameter which would include a Hugging Face token. For example: ```shell zenml annotator register argilla --flavor argilla --authentication_secret=argilla_secrets --instance_url="https://[your-owner-name]-[your_space_name].hf.space" --headers='{"Authorization": "Bearer {[your_hugging_face_token]}"}' ``` Finally, add all these components to a stack and set it as your active stack. For example: ```shell zenml stack copy default annotation # this must be done separately so that the other required stack components are first registered zenml stack update annotation -an zenml stack set annotation # optionally also zenml stack describe ``` Now if you run a simple CLI command like `zenml annotator dataset list` this should work without any errors. You're ready to use your annotator in your ML workflow! ### How do you use it? ZenML supports access to your data and annotations via the `zenml annotator ...` CLI command. We have also implemented an interface to some of the common Argilla functionality via the ZenML SDK. You can access information about the datasets you're using with the `zenml annotator dataset list`. To work on annotation for a particular dataset, you can run `zenml annotator dataset annotate `. This will open the Argilla web interface for you to start annotating the dataset. #### Argilla Annotator Stack Component Our Argilla annotator component inherits from the `BaseAnnotator` class. There are some methods that are core methods that must be defined, like being able to register or get a dataset. Most annotators handle things like the storage of state and have their own custom features, so there are quite a few extra methods specific to Argilla. The core Argilla functionality that's currently enabled includes a way to register your datasets, export any annotations for use in separate steps as well as start the annotator daemon process. (Argilla requires a server to be running in order to use the web interface, and ZenML handles the connection to this server using the details you passed in when registering the component.) #### Argilla Annotator SDK Visit [the SDK docs](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-argilla/) to learn more about the methods that ZenML exposes for the Argilla annotator. To access the SDK through Python, you would first get the client object and then call the methods you need. For example: ```python from zenml.client import Client client = Client() annotator = client.active_stack.annotator # list dataset names dataset_names = annotator.get_dataset_names() # get a specific dataset dataset = annotator.get_dataset("dataset_name") # get the annotations for a dataset annotations = annotator.get_labeled_data(dataset_name="dataset_name") ``` For more detailed information on how to use the Argilla annotator and the functionality it provides, visit the [Argilla documentation](https://docs.argilla.io/en/latest/).
ZenML Scarf
================ File: docs/book/component-guide/annotators/custom.md ================ --- description: Learning how to develop a custom annotator. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a Custom Annotator {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} Annotators are a stack component that enables the use of data annotation as part of your ZenML stack and pipelines. You can use the associated CLI command to launch annotation, configure your datasets and get stats on how many labeled tasks you have ready for use. {% hint style="warning" %} **Base abstraction in progress!** We are actively working on the base abstraction for the annotators, which will be available soon. As a result, their extension is not possible at the moment. If you would like to use an annotator in your stack, please check the list of already available feature stores down below. {% endhint %}
ZenML Scarf
================ File: docs/book/component-guide/annotators/label-studio.md ================ --- description: Annotating data using Label Studio. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Label Studio Label Studio is one of the leading open-source annotation platforms available to data scientists and ML practitioners. It is used to create or edit datasets that you can then use as part of training or validation workflows. It supports a broad range of annotation types, including: * Computer Vision (image classification, object detection, semantic segmentation) * Audio & Speech (classification, speaker diarization, emotion recognition, audio transcription) * Text / NLP (classification, NER, question answering, sentiment analysis) * Time Series (classification, segmentation, event recognition) * Multi-Modal / Domain (dialogue processing, OCR, time series with reference) ### When would you want to use it? If you need to label data as part of your ML workflow, that is the point at which you could consider adding the optional annotator stack component as part of your ZenML stack. We currently support the use of annotation at the various stages described in [the main annotators docs page](annotators.md), and also offer custom utility functions to generate Label Studio label config files for image classification and object detection. (More will follow in due course.) The Label Studio integration currently is built to support workflows using the following three cloud artifact stores: AWS S3, GCP/GCS, and Azure Blob Storage. Purely local stacks will currently _not_ work if you want to do add the annotation stack component as part of your stack. ### How to deploy it? The Label Studio Annotator flavor is provided by the Label Studio ZenML integration, you need to install it, to be able to register it as an Annotator and add it to your stack: ```shell zenml integration install label_studio ``` You will then need to obtain your Label Studio API key. This will give you access to the web annotation interface. (The following steps apply to a local instance of Label Studio, but feel free to obtain your API key directly from your deployed instance if that's what you are using.) ```shell git clone https://github.com/HumanSignal/label-studio.git cd label-studio docker-compose up -d # starts label studio at http://localhost:8080 ``` Then visit [http://localhost:8080/](http://localhost:8080/) to log in, and then visit [http://localhost:8080/user/account](http://localhost:8080/user/account) and get your Label Studio API key (from the upper right-hand corner). You will need it for the next step. Keep the Label Studio server running, because the ZenML Label Studio annotator will use it as the backend. At this point you should register the API key under a custom secret name, making sure to replace the two parts in `<>` with whatever you choose: ```shell zenml secret create label_studio_secrets --api_key="" ``` Then register your annotator with ZenML: ```shell zenml annotator register label_studio --flavor label_studio --authentication_secret="label_studio_secrets" --port=8080 # for deployed instances of Label Studio, you can also pass in the URL as follows, for example: # zenml annotator register label_studio --flavor label_studio --authentication_secret="" --instance_url="" --port=80 ``` When using a deployed instance of Label Studio, the instance URL must be specified without any trailing `/` at the end. You should specify the port, for example, port 80 for a standard HTTP connection. For a Hugging Face deployment (the easiest way to get going with Label Studio), please read the [Hugging Face deployment documentation](https://huggingface.co/docs/hub/spaces-sdks-docker-label-studio). Finally, add all these components to a stack and set it as your active stack. For example: ```shell zenml stack copy default annotation zenml stack update annotation -a # this must be done separately so that the other required stack components are first registered zenml stack update annotation -an zenml stack set annotation # optionally also zenml stack describe ``` Now if you run a simple CLI command like `zenml annotator dataset list` this should work without any errors. You're ready to use your annotator in your ML workflow! ### How do you use it? ZenML assumes that users have registered a cloud artifact store and an annotator as described above. ZenML currently only supports this setup, but we will add in the fully local stack option in the future. ZenML supports access to your data and annotations via the `zenml annotator ...` CLI command. You can access information about the datasets you're using with the `zenml annotator dataset list`. To work on annotation for a particular dataset, you can run `zenml annotator dataset annotate `. [Our computer vision end to end example](https://github.com/zenml-io/zenml-projects/tree/main/end-to-end-computer-vision) is the best place to see how all the pieces of making this integration work fit together. What follows is an overview of some key components to the Label Studio integration and how it can be used. #### Label Studio Annotator Stack Component Our Label Studio annotator component inherits from the `BaseAnnotator` class. There are some methods that are core methods that must be defined, like being able to register or get a dataset. Most annotators handle things like the storage of state and have their own custom features, so there are quite a few extra methods specific to Label Studio. The core Label Studio functionality that's currently enabled includes a way to register your datasets, export any annotations for use in separate steps as well as start the annotator daemon process. (Label Studio requires a server to be running in order to use the web interface, and ZenML handles the provisioning of this server locally using the details you passed in when registering the component unless you've specified that you want to use a deployed instance.) #### Standard Steps ZenML offers some standard steps (and their associated config objects) which will get you up and running with the Label Studio integration quickly. These include: * `LabelStudioDatasetRegistrationConfig` - a step config object to be used when registering a dataset with Label studio using the `get_or_create_dataset` step * `LabelStudioDatasetSyncConfig` - a step config object to be used when registering a dataset with Label studio using the `sync_new_data_to_label_studio` step. Note that this requires a ZenML secret to have been pre-registered with your artifact store as being the one that holds authentication secrets specific to your particular cloud provider. (Label Studio provides some documentation on what permissions these secrets require [here](https://labelstud.io/guide/tasks.html).) * `get_or_create_dataset` step - This takes a `LabelStudioDatasetRegistrationConfig` config object which includes the name of the dataset. If it exists, this step will return the name, but if it doesn't exist then ZenML will register the dataset along with the appropriate label config with Label Studio. * `get_labeled_data` step - This step will get all labeled data available for a particular dataset. Note that these are output in a Label Studio annotation format, which will subsequently be converted into a format appropriate for your specific use case. * `sync_new_data_to_label_studio` step - This step is for ensuring that ZenML is handling the annotations and that the files being used are stored and synced with the ZenML cloud artifact store. This is an important step as part of a continuous annotation workflow since you want all the subsequent steps of your workflow to remain in sync with whatever new annotations are being made or have been created. #### Helper Functions Label Studio requires the use of what it calls 'label config' when you are creating/registering your dataset. These are strings containing HTML-like syntax that allow you to define a custom interface for your annotation. ZenML provides three helper functions that will construct these label config strings in the case of object detection, image classification, and OCR. See the [`integrations.label_studio.label_config_generators`](https://github.com/zenml-io/zenml/blob/main/src/zenml/integrations/label_studio/label_config_generators/label_config_generators.py) module for those three functions.
ZenML Scarf
================ File: docs/book/component-guide/annotators/pigeon.md ================ --- description: Annotating data using Pigeon. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Pigeon Pigeon is a lightweight, open-source annotation tool designed for quick and easy labeling of data directly within Jupyter notebooks. It provides a simple and intuitive interface for annotating various types of data, including: * Text Classification * Image Classification * Text Captioning ### When would you want to use it? ![Pigeon annotator interface](../../.gitbook/assets/pigeon.png) If you need to label a small to medium-sized dataset as part of your ML workflow and prefer the convenience of doing it directly within your Jupyter notebook, Pigeon is a great choice. It is particularly useful for: * Quick labeling tasks that don't require a full-fledged annotation platform * Iterative labeling during the exploratory phase of your ML project * Collaborative labeling within a Jupyter notebook environment ### How to deploy it? To use the Pigeon annotator, you first need to install the ZenML Pigeon integration: ```shell zenml integration install pigeon ``` Next, register the Pigeon annotator with ZenML, specifying the output directory where the annotation files will be stored: ```shell zenml annotator register pigeon --flavor pigeon --output_dir="path/to/dir" ``` Note that the `output_dir` is relative to the repository or notebook root. Finally, add the Pigeon annotator to your stack and set it as the active stack: ```shell zenml stack update --annotator pigeon ``` Now you're ready to use the Pigeon annotator in your ML workflow! ### How do you use it? With the Pigeon annotator registered and added to your active stack, you can easily access it using the ZenML client within your Jupyter notebook. For text classification tasks, you can launch the Pigeon annotator as follows: ````python from zenml.client import Client annotator = Client().active_stack.annotator annotations = annotator.annotate( data=[ 'I love this movie', 'I was really disappointed by the book' ], options=[ 'positive', 'negative' ] ) ```` For image classification tasks, you can provide a custom display function to render the images: ````python from zenml.client import Client from IPython.display import display, Image annotator = Client().active_stack.annotator annotations = annotator.annotate( data=[ '/path/to/image1.png', '/path/to/image2.png' ], options=[ 'cat', 'dog' ], display_fn=lambda filename: display(Image(filename)) ) ```` The `launch` method returns the annotations as a list of tuples, where each tuple contains the data item and its corresponding label. You can also use the `zenml annotator dataset` commands to manage your datasets: * `zenml annotator dataset list` - List all available datasets * `zenml annotator dataset delete ` - Delete a specific dataset * `zenml annotator dataset stats ` - Get statistics for a specific dataset Annotation files are saved as JSON files in the specified output directory. Each annotation file represents a dataset, with the filename serving as the dataset name. ## Acknowledgements Pigeon was created by [Anastasis Germanidis](https://github.com/agermanidis) and released as a [Python package](https://pypi.org/project/pigeon-jupyter/) and [Github repository](https://github.com/agermanidis/pigeon). It is licensed under the Apache License. It has been updated to work with more recent `ipywidgets` versions and some small UI improvements were added. We are grateful to Anastasis for creating this tool and making it available to the community.
ZenML Scarf
================ File: docs/book/component-guide/annotators/prodigy.md ================ --- description: Annotating data using Prodigy. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Prodigy [Prodigy](https://prodi.gy/) is a modern annotation tool for creating training and evaluation data for machine learning models. You can also use Prodigy to help you inspect and clean your data, do error analysis and develop rule-based systems to use in combination with your statistical models. ![Prodigy Annotator](../../.gitbook/assets/prodigy-annotator.png) {% hint style="info" %} Prodigy is a paid annotation tool. You will need a Prodigy is a paid tool. A license is required to download and use it with ZenML. {% endhint %} The Prodigy Python library includes a range of pre-built workflows and command-line commands for various tasks, and well-documented components for implementing your own workflow scripts. Your scripts can specify how the data is loaded and saved, change which questions are asked in the annotation interface, and can even define custom HTML and JavaScript to change the behavior of the front-end. The web application is optimized for fast, intuitive and efficient annotation. ### When would you want to use it? If you need to label data as part of your ML workflow, that is the point at which you could consider adding the optional annotator stack component as part of your ZenML stack. ### How to deploy it? The Prodigy Annotator flavor is provided by the Prodigy ZenML integration. You need to install it to be able to register it as an Annotator and add it to your stack: ```shell zenml integration export-requirements --output-file prodigy-requirements.txt prodigy ``` Note that you'll need to install Prodigy separately since it requires a license. Please [visit the Prodigy docs](https://prodi.gy/docs/install) for information on how to install it. Currently Prodigy also requires the `urllib3<2` dependency, so make sure to install that. Then register your annotator with ZenML: ```shell zenml annotator register prodigy --flavor prodigy # optionally also pass in --custom_config_path="" ``` See https://prodi.gy/docs/install#config for more on custom Prodigy config files. Passing a `custom_config_path` allows you to override the default Prodigy config. Finally, add all these components to a stack and set it as your active stack. For example: ```shell zenml stack copy default annotation zenml stack update annotation -an prodigy zenml stack set annotation # optionally also zenml stack describe ``` Now if you run a simple CLI command like `zenml annotator dataset list` this should work without any errors. You're ready to use your annotator in your ML workflow! ### How do you use it? With Prodigy, there is no need to specially start the annotator ahead of time like with [Label Studio](label-studio.md). Instead, just use Prodigy as per the [Prodigy docs](https://prodi.gy) and then you can use the ZenML wrapper / API to get your labeled data etc using our Python methods. ZenML supports access to your data and annotations via the `zenml annotator ...` CLI command. You can access information about the datasets you're using with the `zenml annotator dataset list`. To work on annotation for a particular dataset, you can run `zenml annotator dataset annotate `. This is the equivalent of running `prodigy ` in the terminal. For example, you might run: ```shell zenml annotator dataset annotate your_dataset --command="textcat.manual news_topics ./news_headlines.jsonl --label Technology,Politics,Economy,Entertainment" ``` This would launch the Prodigy interface for [the `textcat.manual` recipe](https://prodi.gy/docs/recipes#textcat-manual) with the `news_topics` dataset and the labels `Technology`, `Politics`, `Economy`, and `Entertainment`. The data would be loaded from the `news_headlines.jsonl` file. A common workflow for Prodigy is to annotate data as you would usually do, and then use the connection into ZenML to import those annotations within a step in your pipeline (if running locally). For example, within a ZenML step: ```python from typing import List, Dict, Any from zenml import step from zenml.client import Client @step def import_annotations() -> List[Dict[str, Any]: zenml_client = Client() annotations = zenml_client.active_stack.annotator.get_labeled_data(dataset_name="my_dataset") # Do something with the annotations return annotations ``` If you're running in a cloud environment, you can manually export the annotations, store them somewhere in a cloud environment and then reference or use those within ZenML. The precise way you do this will be very case-dependent, however, so it's difficult to provide a one-size-fits-all solution. #### Prodigy Annotator Stack Component Our Prodigy annotator component inherits from the `BaseAnnotator` class. There are some methods that are core methods that must be defined, like being able to register or get a dataset. Most annotators handle things like the storage of state and have their own custom features, so there are quite a few extra methods specific to Prodigy. The core Prodigy functionality that's currently enabled from within the `annotator` stack component interface includes a way to register your datasets and export any annotations for use in separate steps.
ZenML Scarf
================ File: docs/book/component-guide/artifact-stores/artifact-stores.md ================ --- description: Setting up a persistent storage for your artifacts. icon: folder-closed --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Artifact Stores The Artifact Store is a central component in any MLOps stack. As the name suggests, it acts as a data persistence layer where artifacts (e.g. datasets, models) ingested or generated by the machine learning pipelines are stored. ZenML automatically serializes and saves the data circulated through your pipelines in the Artifact Store: datasets, models, data profiles, data and model validation reports, and generally any object that is returned by a pipeline step. This is coupled with tracking in ZenML to provide extremely useful features such as caching and provenance/lineage tracking and pipeline reproducibility. {% hint style="info" %} Not all objects returned by pipeline steps are physically stored in the Artifact Store, nor do they have to be. How artifacts are serialized and deserialized and where their contents are stored are determined by the particular implementation of the [Materializer](../../how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md) associated with the artifact data type. The majority of Materializers shipped with ZenML use the Artifact Store which is part of the active Stack as the location where artifacts are kept. If you need to store _a particular type of pipeline artifact_ in a different medium (e.g. use an external model registry to store model artifacts, or an external data lake or data warehouse to store dataset artifacts), you can write your own [Materializer](../../how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md) to implement the custom logic required for it. In contrast, if you need to use an entirely different storage backend to store artifacts, one that isn't already covered by one of the ZenML integrations, you can [extend the Artifact Store abstraction](custom.md) to provide your own Artifact Store implementation. {% endhint %} In addition to pipeline artifacts, the Artifact Store may also be used as storage backed by other specialized stack components that need to store their data in the form of persistent object storage. The [Great Expectations Data Validator](../data-validators/great-expectations.md) is such an example. Related concepts: * the Artifact Store is a type of Stack Component that needs to be registered as part of your ZenML [Stack](../../user-guide/production-guide/understand-stacks.md). * the objects circulated through your pipelines are serialized and stored in the Artifact Store using [Materializer](../../how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md). Materializers implement the logic required to serialize and deserialize the artifact contents and to store them and retrieve their contents to/from the Artifact Store. ### When to use it The Artifact Store is a mandatory component in the ZenML stack. It is used to store all artifacts produced by pipeline runs, and you are required to configure it in all of your stacks. #### Artifact Store Flavors Out of the box, ZenML comes with a `local` artifact store already part of the default stack that stores artifacts on your local filesystem. Additional Artifact Stores are provided by integrations: | Artifact Store | Flavor | Integration | URI Schema(s) | Notes | | ---------------------------------- | -------- | ----------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------- | | [Local](local.md) | `local` | _built-in_ | None | This is the default Artifact Store. It stores artifacts on your local filesystem. Should be used only for running ZenML locally. | | [Amazon S3](s3.md) | `s3` | `s3` | `s3://` | Uses AWS S3 as an object store backend | | [Google Cloud Storage](gcp.md) | `gcp` | `gcp` | `gs://` | Uses Google Cloud Storage as an object store backend | | [Azure](azure.md) | `azure` | `azure` | `abfs://`, `az://` | Uses Azure Blob Storage as an object store backend | | [Custom Implementation](custom.md) | _custom_ | | _custom_ | Extend the Artifact Store abstraction and provide your own implementation | If you would like to see the available flavors of Artifact Stores, you can use the command: ```shell zenml artifact-store flavor list ``` {% hint style="info" %} Every Artifact Store has a `path` attribute that must be configured when it is registered with ZenML. This is a URI pointing to the root path where all objects are stored in the Artifact Store. It must use a URI schema that is supported by the Artifact Store flavor. For example, the S3 Artifact Store will need a URI that contains the `s3://` schema: ```shell zenml artifact-store register s3_store -f s3 --path s3://my_bucket ``` {% endhint %} ### How to use it The Artifact Store provides low-level object storage services for other ZenML mechanisms. When you develop ZenML pipelines, you normally don't even have to be aware of its existence or interact with it directly. ZenML provides higher-level APIs that can be used as an alternative to store and access artifacts: * return one or more objects from your pipeline steps to have them automatically saved in the active Artifact Store as pipeline artifacts. * [retrieve pipeline artifacts](../../how-to/data-artifact-management/handle-data-artifacts/load-artifacts-into-memory.md) from the active Artifact Store after a pipeline run is complete. You will probably need to interact with the [low-level Artifact Store API](artifact-stores.md#the-artifact-store-api) directly: * if you implement custom [Materializers](../../how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md) for your artifact data types * if you want to store custom objects in the Artifact Store #### The Artifact Store API All ZenML Artifact Stores implement [the same IO API](custom.md) that resembles a standard file system. This allows you to access and manipulate the objects stored in the Artifact Store in the same manner you would normally handle files on your computer and independently of the particular type of Artifact Store that is configured in your ZenML stack. Accessing the low-level Artifact Store API can be done through the following Python modules: * `zenml.io.fileio` provides low-level utilities for manipulating Artifact Store objects (e.g. `open`, `copy`, `rename` , `remove`, `mkdir`). These functions work seamlessly across Artifact Stores types. They have the same signature as the [Artifact Store abstraction methods](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-artifact\_stores/#zenml.artifact\_stores.base\_artifact\_store.BaseArtifactStore) ( in fact, they are one and the same under the hood). * [zenml.utils.io\_utils](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-utils/#zenml.utils.io\_utils) includes some higher-level helper utilities that make it easier to find and transfer objects between the Artifact Store and the local filesystem or memory. {% hint style="info" %} When calling the Artifact Store API, you should always use URIs that are relative to the Artifact Store root path, otherwise, you risk using an unsupported protocol or storing objects outside the store. You can use the `Repository` singleton to retrieve the root path of the active Artifact Store and then use it as a base path for artifact URIs, e.g.: ```python import os from zenml.client import Client from zenml.io import fileio root_path = Client().active_stack.artifact_store.path artifact_contents = "example artifact" artifact_path = os.path.join(root_path, "artifacts", "examples") artifact_uri = os.path.join(artifact_path, "test.txt") fileio.makedirs(artifact_path) with fileio.open(artifact_uri, "w") as f: f.write(artifact_contents) ``` When using the Artifact Store API to write custom Materializers, the base artifact URI path is already provided. See the documentation on [Materializers](../../how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md) for an example. {% endhint %} The following are some code examples showing how to use the Artifact Store API for various operations: * creating folders, writing and reading data directly to/from an artifact store object ```python import os from zenml.utils import io_utils from zenml.io import fileio from zenml.client import Client root_path = Client().active_stack.artifact_store.path artifact_contents = "example artifact" artifact_path = os.path.join(root_path, "artifacts", "examples") artifact_uri = os.path.join(artifact_path, "test.txt") fileio.makedirs(artifact_path) io_utils.write_file_contents_as_string(artifact_uri, artifact_contents) ``` ```python import os from zenml.utils import io_utils from zenml.client import Client root_path = Client().active_stack.artifact_store.path artifact_path = os.path.join(root_path, "artifacts", "examples") artifact_uri = os.path.join(artifact_path, "test.txt") artifact_contents = io_utils.read_file_contents_as_string(artifact_uri) ``` * using a temporary local file/folder to serialize and copy in-memory objects to/from the artifact store (heavily used in Materializers to transfer information between the Artifact Store and external libraries that don't support writing/reading directly to/from the artifact store backend): ```python import os import tempfile import external_lib root_path = Repository().active_stack.artifact_store.path artifact_path = os.path.join(root_path, "artifacts", "examples") artifact_uri = os.path.join(artifact_path, "test.json") fileio.makedirs(artifact_path) with tempfile.NamedTemporaryFile( mode="w", suffix=".json", delete=True ) as f: external_lib.external_object.save_to_file(f.name) # Copy it into artifact store fileio.copy(f.name, artifact_uri) ``` ```python import os import tempfile import external_lib root_path = Repository().active_stack.artifact_store.path artifact_path = os.path.join(root_path, "artifacts", "examples") artifact_uri = os.path.join(artifact_path, "test.json") with tempfile.NamedTemporaryFile( mode="w", suffix=".json", delete=True ) as f: # Copy the serialized object from the artifact store fileio.copy(artifact_uri, f.name) external_lib.external_object.load_from_file(f.name) ```
ZenML Scarf
================ File: docs/book/component-guide/artifact-stores/azure.md ================ --- description: Storing artifacts using Azure Blob Storage --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Azure Blob Storage The Azure Artifact Store is an [Artifact Store](./artifact-stores.md) flavor provided with the Azure ZenML integration that uses [the Azure Blob Storage managed object storage service](https://azure.microsoft.com/en-us/services/storage/blobs/) to store ZenML artifacts in an Azure Blob Storage container. ### When would you want to use it? Running ZenML pipelines with [the local Artifact Store](local.md) is usually sufficient if you just want to evaluate ZenML or get started quickly without incurring the trouble and the cost of employing cloud storage services in your stack. However, the local Artifact Store becomes insufficient or unsuitable if you have more elaborate needs for your project: * if you want to share your pipeline run results with other team members or stakeholders inside or outside your organization * if you have other components in your stack that are running remotely (e.g. a Kubeflow or Kubernetes Orchestrator running in a public cloud). * if you outgrow what your local machine can offer in terms of storage space and need to use some form of private or public storage service that is shared with others * if you are running pipelines at scale and need an Artifact Store that can handle the demands of production-grade MLOps In all these cases, you need an Artifact Store that is backed by a form of public cloud or self-hosted shared object storage service. You should use the Azure Artifact Store when you decide to keep your ZenML artifacts in a shared object storage and if you have access to the Azure Blob Storage managed service. You should consider one of the other [Artifact Store flavors](./artifact-stores.md#artifact-store-flavors) if you don't have access to the Azure Blob Storage service. ### How do you deploy it? {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including an Azure Artifact Store? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), the [stack registration wizard](../../how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md), or [the ZenML Azure Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} The Azure Artifact Store flavor is provided by the Azure ZenML integration, you need to install it on your local machine to be able to register an Azure Artifact Store and add it to your stack: ```shell zenml integration install azure -y ``` The only configuration parameter mandatory for registering an Azure Artifact Store is the root path URI, which needs to point to an Azure Blog Storage container and take the form `az://container-name` or `abfs://container-name`. Please read [the Azure Blob Storage documentation](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-portal) on how to configure an Azure Blob Storage container. With the URI to your Azure Blob Storage container known, registering an Azure Artifact Store can be done as follows: ```shell # Register the Azure artifact store zenml artifact-store register az_store -f azure --path=az://container-name # Register and set a stack with the new artifact store zenml stack register custom_stack -a az_store ... --set ``` Depending on your use case, however, you may also need to provide additional configuration parameters pertaining to [authentication](azure.md#authentication-methods) to match your deployment scenario. #### Authentication Methods Integrating and using an Azure Artifact Store in your pipelines is not possible without employing some form of authentication. If you're looking for a quick way to get started locally, you can use the _Implicit Authentication_ method. However, the recommended way to authenticate to the Azure cloud platform is through [an Azure Service Connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md). This is particularly useful if you are configuring ZenML stacks that combine the Azure Artifact Store with other remote stack components also running in Azure. You will need the following information to configure Azure credentials for ZenML, depending on which type of Azure credentials you want to use: * an Azure connection string * an Azure account key * the client ID, client secret and tenant ID of the Azure service principal For more information on how to retrieve information about your Azure Storage Account and Access Key or connection string, please refer to this [Azure guide](https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python?tabs=environment-variable-windows#copy-your-credentials-from-the-azure-portal). For information on how to configure an Azure service principal, please consult the [Azure documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal). {% tabs %} {% tab title="Implicit Authentication" %} This method uses the implicit Azure authentication available _in the environment where the ZenML code is running_. On your local machine, this is the quickest way to configure an Azure Artifact Store. You don't need to supply credentials explicitly when you register the Azure Artifact Store, instead, you have to set one of the following sets of environment variables: * to use [an Azure storage account key](https://learn.microsoft.com/en-us/azure/storage/common/storage-account-keys-manage) , set `AZURE_STORAGE_ACCOUNT_NAME` to your account name and one of `AZURE_STORAGE_ACCOUNT_KEY` or `AZURE_STORAGE_SAS_TOKEN` to the Azure key value. * to use [an Azure storage account key connection string](https://learn.microsoft.com/en-us/azure/storage/common/storage-account-keys-manage) , set `AZURE_STORAGE_CONNECTION_STRING` to your Azure Storage Key connection string * to use [Azure Service Principal credentials](https://learn.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals) , [create an Azure Service Principal](https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal) and then set `AZURE_STORAGE_ACCOUNT_NAME` to your account name and `AZURE_STORAGE_CLIENT_ID` , `AZURE_STORAGE_CLIENT_SECRET` and `AZURE_STORAGE_TENANT_ID` to the client ID, secret and tenant ID of your service principal {% hint style="warning" %} Certain dashboard functionality, such as visualizing or deleting artifacts, is not available when using an implicitly authenticated artifact store together with a deployed ZenML server because the ZenML server will not have permission to access the filesystem. The implicit authentication method also needs to be coordinated with other stack components that are highly dependent on the Artifact Store and need to interact with it directly to the function. If these components are not running on your machine, they do not have access to the local environment variables and will encounter authentication failures while trying to access the Azure Artifact Store: * [Orchestrators](../orchestrators/orchestrators.md) need to access the Artifact Store to manage pipeline artifacts * [Step Operators](../step-operators/step-operators.md) need to access the Artifact Store to manage step-level artifacts * [Model Deployers](../model-deployers/model-deployers.md) need to access the Artifact Store to load served models To enable these use cases, it is recommended to use [an Azure Service Connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md) to link your Azure Artifact Store to the remote Azure Blob storage container. {% endhint %} {% endtab %} {% tab title="Azure Service Connector (recommended)" %} To set up the Azure Artifact Store to authenticate to Azure and access an Azure Blob storage container, it is recommended to leverage the many features provided by [the Azure Service Connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md) such as auto-configuration, best security practices regarding long-lived credentials and reusing the same credentials across multiple stack components. If you don't already have an Azure Service Connector configured in your ZenML deployment, you can register one using the interactive CLI command. You have the option to configure an Azure Service Connector that can be used to access more than one Azure blob storage container or even more than one type of Azure resource: ```sh zenml service-connector register --type azure -i ``` A non-interactive CLI example that uses [Azure Service Principal credentials](https://learn.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals) to configure an Azure Service Connector targeting a single Azure Blob storage container is: ```sh zenml service-connector register --type azure --auth-method service-principal --tenant_id= --client_id= --client_secret= --resource-type blob-container --resource-id ``` {% code title="Example Command Output" %} ``` $ zenml service-connector register azure-blob-demo --type azure --auth-method service-principal --tenant_id=a79f3633-8f45-4a74-a42e-68871c17b7fb --client_id=8926254a-8c3f-430a-a2fd-bdab234d491e --client_secret=AzureSuperSecret --resource-type blob-container --resource-id az://demo-zenmlartifactstore Successfully registered service connector `azure-blob-demo` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠───────────────────┼──────────────────────────────┨ ┃ πŸ“¦ blob-container β”‚ az://demo-zenmlartifactstore ┃ ┗━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} > **Note**: Please remember to grant the Azure service principal permissions to read and write to your Azure Blob storage container as well as to list accessible storage accounts and Blob containers. For a full list of permissions required to use an AWS Service Connector to access one or more S3 buckets, please refer to the [Azure Service Connector Blob storage container resource type documentation](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md#azure-blob-storage-container) or read the documentation available in the interactive CLI commands and dashboard. The Azure Service Connector supports [many different authentication methods](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md#authentication-methods) with different levels of security and convenience. You should pick the one that best fits your use-case. If you already have one or more Azure Service Connectors configured in your ZenML deployment, you can check which of them can be used to access the Azure Blob storage container you want to use for your Azure Artifact Store by running e.g.: ```sh zenml service-connector list-resources --resource-type blob-container ``` {% code title="Example Command Output" %} ``` The following 'blob-container' resources can be accessed by service connectors: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼─────────────────────────┼────────────────┼───────────────────┼──────────────────────────────┨ ┃ 273d2812-2643-4446-82e6-6098b8ccdaa4 β”‚ azure-service-principal β”‚ πŸ‡¦ azure β”‚ πŸ“¦ blob-container β”‚ az://demo-zenmlartifactstore ┃ ┠──────────────────────────────────────┼─────────────────────────┼────────────────┼───────────────────┼──────────────────────────────┨ ┃ f6b329e1-00f7-4392-94c9-264119e672d0 β”‚ azure-blob-demo β”‚ πŸ‡¦ azure β”‚ πŸ“¦ blob-container β”‚ az://demo-zenmlartifactstore ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} After having set up or decided on an Azure Service Connector to use to connect to the target Azure Blob storage container, you can register the Azure Artifact Store as follows: ```sh # Register the Azure artifact-store and reference the target blob storage container zenml artifact-store register -f azure \ --path='az://your-container' # Connect the Azure artifact-store to the target container via an Azure Service Connector zenml artifact-store connect -i ``` A non-interactive version that connects the Azure Artifact Store to a target blob storage container through an Azure Service Connector: ```sh zenml artifact-store connect --connector ``` {% code title="Example Command Output" %} ``` $ zenml artifact-store connect azure-blob-demo --connector azure-blob-demo Successfully connected artifact store `azure-blob-demo` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼─────────────────┼────────────────┼───────────────────┼──────────────────────────────┨ ┃ f6b329e1-00f7-4392-94c9-264119e672d0 β”‚ azure-blob-demo β”‚ πŸ‡¦ azure β”‚ πŸ“¦ blob-container β”‚ az://demo-zenmlartifactstore ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} As a final step, you can use the Azure Artifact Store in a ZenML Stack: ```sh # Register and set a stack with the new artifact store zenml stack register -a ... --set ``` {% endtab %} {% tab title="ZenML Secret" %} When you register the Azure Artifact Store, you can create a [ZenML Secret](../../getting-started/deploying-zenml/secret-management.md) to store a variety of Azure credentials and then reference it in the Artifact Store configuration: * to use [an Azure storage account key](https://learn.microsoft.com/en-us/azure/storage/common/storage-account-keys-manage) , set `account_name` to your account name and one of `account_key` or `sas_token` to the Azure key or SAS token value as attributes in the ZenML secret * to use [an Azure storage account key connection string](https://learn.microsoft.com/en-us/azure/storage/common/storage-account-keys-manage) , configure the `connection_string` attribute in the ZenML secret to your Azure Storage Key connection string * to use [Azure Service Principal credentials](https://learn.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals) , [create an Azure Service Principal](https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal) and then set `account_name` to your account name and `client_id`, `client_secret` and `tenant_id` to the client ID, secret and tenant ID of your service principal in the ZenML secret This method has some advantages over the implicit authentication method: * you don't need to install and configure the Azure CLI on your host * you don't need to care about enabling your other stack components (orchestrators, step operators and model deployers) to have access to the artifact store through Azure Managed Identities * you can combine the Azure artifact store with other stack components that are not running in Azure Configuring Azure credentials in a ZenML secret and then referencing them in the Artifact Store configuration could look like this: ```shell # Store the Azure storage account key in a ZenML secret zenml secret create az_secret \ --account_name='' \ --account_key='' # or if you want to use a connection string zenml secret create az_secret \ --connection_string='' # or if you want to use Azure ServicePrincipal credentials zenml secret create az_secret \ --account_name='' \ --tenant_id='' \ --client_id='' \ --client_secret='' # Alternatively for providing key-value pairs, you can utilize the '--values' option by specifying a file path containing # key-value pairs in either JSON or YAML format. # File content example: {"account_name":"",...} zenml secret create az_secret \ --values=@path/to/file.txt # Register the Azure artifact store and reference the ZenML secret zenml artifact-store register az_store -f azure \ --path='az://your-container' \ --authentication_secret=az_secret # Register and set a stack with the new artifact store zenml stack register custom_stack -a az_store ... --set ``` {% endtab %} {% endtabs %} For more, up-to-date information on the Azure Artifact Store implementation and its configuration, you can have a look at [the SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-azure/#zenml.integrations.azure.artifact\_stores) . ### How do you use it? Aside from the fact that the artifacts are stored in Azure Blob Storage, using the Azure Artifact Store is no different from [using any other flavor of Artifact Store](./artifact-stores.md#how-to-use-it).
ZenML Scarf
================ File: docs/book/component-guide/artifact-stores/custom.md ================ --- description: Learning how to develop a custom artifact store. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a custom artifact store {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} ZenML comes equipped with [Artifact Store implementations](./artifact-stores.md#artifact-store-flavors) that you can use to store artifacts on a local filesystem or in the managed AWS, GCP, or Azure cloud object storage services. However, if you need to use a different type of object storage service as a backend for your ZenML Artifact Store, you can extend ZenML to provide your own custom Artifact Store implementation. ### Base Abstraction The Artifact Store establishes one of the main components in every ZenML stack. Now, let us take a deeper dive into the fundamentals behind its abstraction, namely [the `BaseArtifactStore` class](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-artifact\_stores/#zenml.artifact\_stores.base\_artifact\_store.BaseArtifactStore): 1. As ZenML only supports filesystem-based artifact stores, it features a configuration parameter called `path`, which will indicate the root path of the artifact store. When registering an artifact store, users will have to define this parameter. 2. Moreover, there is another variable in the config class called `SUPPORTED_SCHEMES`. This is a class variable that needs to be defined in every subclass of the base artifact store configuration. It indicates the supported file path schemes for the corresponding implementation. For instance, for the Azure artifact store, this set will be defined as `{"abfs://", "az://"}`. 3. Lastly, the base class features a set of `abstractmethod`s: `open`, `copyfile`,`exists`,`glob`,`isdir`,`listdir` ,`makedirs`,`mkdir`,`remove`, `rename`,`rmtree`,`stat`,`walk`. In the implementation of every `ArtifactStore` flavor, it is required to define these methods with respect to the flavor at hand. Putting all these considerations together, we end up with the following implementation: ```python from zenml.enums import StackComponentType from zenml.stack import StackComponent, StackComponentConfig PathType = Union[bytes, str] class BaseArtifactStoreConfig(StackComponentConfig): """Config class for `BaseArtifactStore`.""" path: str SUPPORTED_SCHEMES: ClassVar[Set[str]] class BaseArtifactStore(StackComponent): """Base class for all ZenML artifact stores.""" @abstractmethod def open(self, name: PathType, mode: str = "r") -> Any: """Open a file at the given path.""" @abstractmethod def copyfile( self, src: PathType, dst: PathType, overwrite: bool = False ) -> None: """Copy a file from the source to the destination.""" @abstractmethod def exists(self, path: PathType) -> bool: """Returns `True` if the given path exists.""" @abstractmethod def glob(self, pattern: PathType) -> List[PathType]: """Return the paths that match a glob pattern.""" @abstractmethod def isdir(self, path: PathType) -> bool: """Returns whether the given path points to a directory.""" @abstractmethod def listdir(self, path: PathType) -> List[PathType]: """Returns a list of files under a given directory in the filesystem.""" @abstractmethod def makedirs(self, path: PathType) -> None: """Make a directory at the given path, recursively creating parents.""" @abstractmethod def mkdir(self, path: PathType) -> None: """Make a directory at the given path; parent directory must exist.""" @abstractmethod def remove(self, path: PathType) -> None: """Remove the file at the given path. Dangerous operation.""" @abstractmethod def rename( self, src: PathType, dst: PathType, overwrite: bool = False ) -> None: """Rename source file to destination file.""" @abstractmethod def rmtree(self, path: PathType) -> None: """Deletes dir recursively. Dangerous operation.""" @abstractmethod def stat(self, path: PathType) -> Any: """Return the stat descriptor for a given file path.""" @abstractmethod def walk( self, top: PathType, topdown: bool = True, onerror: Optional[Callable[..., None]] = None, ) -> Iterable[Tuple[PathType, List[PathType], List[PathType]]]: """Return an iterator that walks the contents of the given directory.""" class BaseArtifactStoreFlavor(Flavor): """Base class for artifact store flavors.""" @property @abstractmethod def name(self) -> Type["BaseArtifactStore"]: """Returns the name of the flavor.""" @property def type(self) -> StackComponentType: """Returns the flavor type.""" return StackComponentType.ARTIFACT_STORE @property def config_class(self) -> Type[StackComponentConfig]: """Config class.""" return BaseArtifactStoreConfig @property @abstractmethod def implementation_class(self) -> Type["BaseArtifactStore"]: """Implementation class.""" ``` {% hint style="info" %} This is a slimmed-down version of the base implementation which aims to highlight the abstraction layer. In order to see the full implementation and get the complete docstrings, please check the [SDK docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-artifact\_stores/#zenml.artifact\_stores.base\_artifact\_store.BaseArtifactStore) . {% endhint %} **The effect on the `zenml.io.fileio`** If you created an instance of an artifact store, added it to your stack, and activated the stack, it will create a filesystem each time you run a ZenML pipeline and make it available to the `zenml.io.fileio` module. This means that when you utilize a method such as `fileio.open(...)` with a file path that starts with one of the `SUPPORTED_SCHEMES` within your steps or materializers, it will be able to use the `open(...)` method that you defined within your artifact store. ### Build your own custom artifact store If you want to implement your own custom Artifact Store, you can follow the following steps: 1. Create a class that inherits from [the `BaseArtifactStore` class](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-artifact\_stores/#zenml.artifact\_stores.base\_artifact\_store.BaseArtifactStore) and implements the abstract methods. 2. Create a class that inherits from [the `BaseArtifactStoreConfig` class](custom.md) and fill in the `SUPPORTED_SCHEMES` based on your file system. 3. Bring both of these classes together by inheriting from [the `BaseArtifactStoreFlavor` class](custom.md). Once you are done with the implementation, you can register it through the CLI. Please ensure you **point to the flavor class via dot notation**: ```shell zenml artifact-store flavor register ``` For example, if your flavor class `MyArtifactStoreFlavor` is defined in `flavors/my_flavor.py`, you'd register it by doing: ```shell zenml artifact-store flavor register flavors.my_flavor.MyArtifactStoreFlavor ``` {% hint style="warning" %} ZenML resolves the flavor class by taking the path where you initialized zenml (via `zenml init`) as the starting point of resolution. Therefore, please ensure you follow [the best practice](../../how-to/infrastructure-deployment/infrastructure-as-code/best-practices.md) of initializing zenml at the root of your repository. If ZenML does not find an initialized ZenML repository in any parent directory, it will default to the current working directory, but usually, it's better to not have to rely on this mechanism and initialize zenml at the root. {% endhint %} Afterward, you should see the new custom artifact store flavor in the list of available artifact store flavors: ```shell zenml artifact-store flavor list ``` {% hint style="warning" %} It is important to draw attention to when and how these base abstractions are coming into play in a ZenML workflow. * The **CustomArtifactStoreFlavor** class is imported and utilized upon the creation of the custom flavor through the CLI. * The **CustomArtifactStoreConfig** class is imported when someone tries to register/update a stack component with this custom flavor. Especially, during the registration process of the stack component, the config will be used to validate the values given by the user. As `Config` objects are inherently `pydantic` objects, you can also add your own custom validators here. * The **CustomArtifactStore** only comes into play when the component is ultimately in use. The design behind this interaction lets us separate the configuration of the flavor from its implementation. This way we can register flavors and components even when the major dependencies behind their implementation are not installed in our local setting (assuming the `CustomArtifactStoreFlavor` and the `CustomArtifactStoreConfig` are implemented in a different module/path than the actual `CustomArtifactStore`). {% endhint %} #### Enabling Artifact Visualizations with Custom Artifact Stores ZenML automatically saves visualizations for many common data types and allows you to view these visualizations in the ZenML dashboard. Under the hood, this works by saving the visualizations together with the artifacts in the artifact store. In order to load and display these visualizations, ZenML needs to be able to load and access the corresponding artifact store. This means that your custom artifact store needs to be configured in a way that allows authenticating to the back-end without relying on the local environment, e.g., by embedding the authentication credentials in the stack component configuration or by referencing a secret. Furthermore, for deployed ZenML instances, you need to install the package dependencies of your artifact store implementation in the environment where you have deployed ZenML. See the [Documentation on deploying ZenML with custom Docker images](../../getting-started/deploying-zenml/deploy-with-custom-image.md) for more information on how to do that.
ZenML Scarf
================ File: docs/book/component-guide/artifact-stores/gcp.md ================ --- description: Storing artifacts using GCP Cloud Storage. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Google Cloud Storage (GCS) The GCS Artifact Store is an [Artifact Store](./artifact-stores.md) flavor provided with the GCP ZenML integration that uses [the Google Cloud Storage managed object storage service](https://cloud.google.com/storage/docs/introduction) to store ZenML artifacts in a GCP Cloud Storage bucket. ### When would you want to use it? Running ZenML pipelines with [the local Artifact Store](local.md) is usually sufficient if you just want to evaluate ZenML or get started quickly without incurring the trouble and the cost of employing cloud storage services in your stack. However, the local Artifact Store becomes insufficient or unsuitable if you have more elaborate needs for your project: * if you want to share your pipeline run results with other team members or stakeholders inside or outside your organization * if you have other components in your stack that are running remotely (e.g. a Kubeflow or Kubernetes Orchestrator running in a public cloud). * if you outgrow what your local machine can offer in terms of storage space and need to use some form of private or public storage service that is shared with others * if you are running pipelines at scale and need an Artifact Store that can handle the demands of production-grade MLOps In all these cases, you need an Artifact Store that is backed by a form of public cloud or self-hosted shared object storage service. You should use the GCS Artifact Store when you decide to keep your ZenML artifacts in a shared object storage and if you have access to the Google Cloud Storage managed service. You should consider one of the other [Artifact Store flavors](./artifact-stores.md#artifact-store-flavors) if you don't have access to the GCP Cloud Storage service. ### How do you deploy it? {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including a GCS Artifact Store? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), the [stack registration wizard](../../how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md), or [the ZenML GCP Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} The GCS Artifact Store flavor is provided by the GCP ZenML integration, you need to install it on your local machine to be able to register a GCS Artifact Store and add it to your stack: ```shell zenml integration install gcp -y ``` The only configuration parameter mandatory for registering a GCS Artifact Store is the root path URI, which needs to point to a GCS bucket and take the form `gs://bucket-name`. Please read [the Google Cloud Storage documentation](https://cloud.google.com/storage/docs/creating-buckets) on how to configure a GCS bucket. With the URI to your GCS bucket known, registering a GCS Artifact Store can be done as follows: ```shell # Register the GCS artifact store zenml artifact-store register gs_store -f gcp --path=gs://bucket-name # Register and set a stack with the new artifact store zenml stack register custom_stack -a gs_store ... --set ``` Depending on your use case, however, you may also need to provide additional configuration parameters pertaining to [authentication](gcp.md#authentication-methods) to match your deployment scenario. #### Authentication Methods Integrating and using a GCS Artifact Store in your pipelines is not possible without employing some form of authentication. If you're looking for a quick way to get started locally, you can use the _Implicit Authentication_ method. However, the recommended way to authenticate to the GCP cloud platform is through [a GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md). This is particularly useful if you are configuring ZenML stacks that combine the GCS Artifact Store with other remote stack components also running in GCP. {% tabs %} {% tab title="Implicit Authentication" %} This method uses the implicit GCP authentication available _in the environment where the ZenML code is running_. On your local machine, this is the quickest way to configure a GCS Artifact Store. You don't need to supply credentials explicitly when you register the GCS Artifact Store, as it leverages the local credentials and configuration that the Google Cloud CLI stores on your local machine. However, you will need to install and set up the Google Cloud CLI on your machine as a prerequisite, as covered in [the Google Cloud documentation](https://cloud.google.com/sdk/docs/install-sdk) , before you register the GCS Artifact Store. {% hint style="warning" %} Certain dashboard functionality, such as visualizing or deleting artifacts, is not available when using an implicitly authenticated artifact store together with a deployed ZenML server because the ZenML server will not have permission to access the filesystem. The implicit authentication method also needs to be coordinated with other stack components that are highly dependent on the Artifact Store and need to interact with it directly to the function. If these components are not running on your machine, they do not have access to the local Google Cloud CLI configuration and will encounter authentication failures while trying to access the GCS Artifact Store: * [Orchestrators](../orchestrators/orchestrators.md) need to access the Artifact Store to manage pipeline artifacts * [Step Operators](../step-operators/step-operators.md) need to access the Artifact Store to manage step-level artifacts * [Model Deployers](../model-deployers/model-deployers.md) need to access the Artifact Store to load served models To enable these use cases, it is recommended to use [a GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) to link your GCS Artifact Store to the remote GCS bucket. {% endhint %} {% endtab %} {% tab title="GCP Service Connector (recommended)" %} To set up the GCS Artifact Store to authenticate to GCP and access a GCS bucket, it is recommended to leverage the many features provided by [the GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) such as auto-configuration, best security practices regarding long-lived credentials and reusing the same credentials across multiple stack components. If you don't already have a GCP Service Connector configured in your ZenML deployment, you can register one using the interactive CLI command. You have the option to configure a GCP Service Connector that can be used to access more than one GCS bucket or even more than one type of GCP resource: ```sh zenml service-connector register --type gcp -i ``` A non-interactive CLI example that leverages [the Google Cloud CLI configuration](https://cloud.google.com/sdk/docs/install-sdk) on your local machine to auto-configure a GCP Service Connector targeting a single GCS bucket is: ```sh zenml service-connector register --type gcp --resource-type gcs-bucket --resource-name --auto-configure ``` {% code title="Example Command Output" %} ``` $ zenml service-connector register gcs-zenml-bucket-sl --type gcp --resource-type gcs-bucket --resource-id gs://zenml-bucket-sl --auto-configure β Έ Registering service connector 'gcs-zenml-bucket-sl'... Successfully registered service connector `gcs-zenml-bucket-sl` with access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠───────────────┼──────────────────────┨ ┃ πŸ“¦ gcs-bucket β”‚ gs://zenml-bucket-sl ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} > **Note**: Please remember to grant the entity associated with your GCP credentials permissions to read and write to your GCS bucket as well as to list accessible GCS buckets. For a full list of permissions required to use a GCP Service Connector to access one or more GCS buckets, please refer to the [GCP Service Connector GCS bucket resource type documentation](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md#gcs-bucket) or read the documentation available in the interactive CLI commands and dashboard. The GCP Service Connector supports [many different authentication methods](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md#authentication-methods) with different levels of security and convenience. You should pick the one that best fits your use case. If you already have one or more GCP Service Connectors configured in your ZenML deployment, you can check which of them can be used to access the GCS bucket you want to use for your GCS Artifact Store by running e.g.: ```sh zenml service-connector list-resources --resource-type gcs-bucket ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼─────────────────────┼────────────────┼───────────────┼─────────────────────────────────────────────────┨ ┃ 7f0c69ba-9424-40ae-8ea6-04f35c2eba9d β”‚ gcp-user-account β”‚ πŸ”΅ gcp β”‚ πŸ“¦ gcs-bucket β”‚ gs://zenml-bucket-sl ┃ ┃ β”‚ β”‚ β”‚ β”‚ gs://zenml-core.appspot.com ┃ ┃ β”‚ β”‚ β”‚ β”‚ gs://zenml-core_cloudbuild ┃ ┃ β”‚ β”‚ β”‚ β”‚ gs://zenml-datasets ┃ ┃ β”‚ β”‚ β”‚ β”‚ gs://zenml-internal-artifact-store ┃ ┃ β”‚ β”‚ β”‚ β”‚ gs://zenml-kubeflow-artifact-store ┃ ┠──────────────────────────────────────┼─────────────────────┼────────────────┼───────────────┼─────────────────────────────────────────────────┨ ┃ 2a0bec1b-9787-4bd7-8d4a-9a47b6f61643 β”‚ gcs-zenml-bucket-sl β”‚ πŸ”΅ gcp β”‚ πŸ“¦ gcs-bucket β”‚ gs://zenml-bucket-sl ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} After having set up or decided on a GCP Service Connector to use to connect to the target GCS bucket, you can register the GCS Artifact Store as follows: ```sh # Register the GCS artifact-store and reference the target GCS bucket zenml artifact-store register -f gcp \ --path='gs://your-bucket' # Connect the GCS artifact-store to the target bucket via a GCP Service Connector zenml artifact-store connect -i ``` A non-interactive version that connects the GCS Artifact Store to a target GCP Service Connector: ```sh zenml artifact-store connect --connector ``` {% code title="Example Command Output" %} ``` $ zenml artifact-store connect gcs-zenml-bucket-sl --connector gcs-zenml-bucket-sl Successfully connected artifact store `gcs-zenml-bucket-sl` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼─────────────────────┼────────────────┼───────────────┼──────────────────────┨ ┃ 2a0bec1b-9787-4bd7-8d4a-9a47b6f61643 β”‚ gcs-zenml-bucket-sl β”‚ πŸ”΅ gcp β”‚ πŸ“¦ gcs-bucket β”‚ gs://zenml-bucket-sl ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} As a final step, you can use the GCS Artifact Store in a ZenML Stack: ```sh # Register and set a stack with the new artifact store zenml stack register -a ... --set ``` {% endtab %} {% tab title="GCP Credentials" %} When you register the GCS Artifact Store, you can [generate a GCP Service Account Key](https://cloud.google.com/docs/authentication/application-default-credentials#attached-sa), store it in a [ZenML Secret](../../getting-started/deploying-zenml/secret-management.md) and then reference it in the Artifact Store configuration. This method has some advantages over the implicit authentication method: * you don't need to install and configure the GCP CLI on your host * you don't need to care about enabling your other stack components (orchestrators, step operators and model deployers) to have access to the artifact store through GCP Service Accounts and Workload Identity * you can combine the GCS artifact store with other stack components that are not running in GCP For this method, you need to [create a user-managed GCP service account](https://cloud.google.com/iam/docs/service-accounts-create), grant it privileges to read and write to your GCS bucket (i.e. use the `Storage Object Admin` role) and then [create a service account key](https://cloud.google.com/iam/docs/keys-create-delete#creating). With the service account key downloaded to a local file, you can register a ZenML secret and reference it in the GCS Artifact Store configuration as follows: ```shell # Store the GCP credentials in a ZenML zenml secret create gcp_secret \ --token=@path/to/service_account_key.json # Register the GCS artifact store and reference the ZenML secret zenml artifact-store register gcs_store -f gcp \ --path='gs://your-bucket' \ --authentication_secret=gcp_secret # Register and set a stack with the new artifact store zenml stack register custom_stack -a gs_store ... --set ``` {% endtab %} {% endtabs %} For more, up-to-date information on the GCS Artifact Store implementation and its configuration, you can have a look at [the SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-gcp/#zenml.integrations.gcp.artifact\_stores.gcp\_artifact\_store) . ### How do you use it? Aside from the fact that the artifacts are stored in GCP Cloud Storage, using the GCS Artifact Store is no different from [using any other flavor of Artifact Store](./artifact-stores.md#how-to-use-it).
ZenML Scarf
================ File: docs/book/component-guide/artifact-stores/local.md ================ --- description: Storing artifacts on your local filesystem. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Local Artifact Store The local Artifact Store is a built-in ZenML [Artifact Store](./artifact-stores.md) flavor that uses a folder on your local filesystem to store artifacts. ### When would you want to use it? The local Artifact Store is a great way to get started with ZenML, as it doesn't require you to provision additional local resources or to interact with managed object-store services like Amazon S3 and Google Cloud Storage. All you need is the local filesystem. You should use the local Artifact Store if you're just evaluating or getting started with ZenML, or if you are still in the experimental phase and don't need to share your pipeline artifacts (dataset, models, etc.) with others. {% hint style="warning" %} The local Artifact Store is not meant to be utilized in production. The local filesystem cannot be shared across your team and the artifacts stored in it cannot be accessed from other machines. This also means that [artifact visualizations](../../how-to/data-artifact-management/visualize-artifacts/README.md) will not be available when using a local Artifact Store through a [ZenML instance deployed in the cloud](../../getting-started/deploying-zenml/README.md). Furthermore, the local Artifact Store doesn't cover services like high-availability, scalability, backup and restore and other features that are expected from a production grade MLOps system. The fact that it stores artifacts on your local filesystem also means that not all stack components can be used in the same stack as a local Artifact Store: * only [Orchestrators](../orchestrators/orchestrators.md) running on the local machine, such as the [local Orchestrator](../orchestrators/local.md), a [local Kubeflow Orchestrator](../orchestrators/kubeflow.md), or a [local Kubernetes Orchestrator](../orchestrators/kubernetes.md) can be combined with a local Artifact Store * only [Model Deployers](../model-deployers/model-deployers.md) that are running locally, such as the [MLflow Model Deployer](../model-deployers/mlflow.md), can be used in combination with a local Artifact Store * [Step Operators](../step-operators/step-operators.md): none of the Step Operators can be used in the same stack as a local Artifact Store, given that their very purpose is to run ZenML steps in remote specialized environments As you transition to a team setting or a production setting, you can replace the local Artifact Store in your stack with one of the other flavors that are better suited for these purposes, with no changes required in your code. {% endhint %} ### How do you deploy it? The `default` stack that comes pre-configured with ZenML already contains a local Artifact Store: ``` $ zenml stack list Running without an active repository root. Using the default local database. ┏━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓ ┃ ACTIVE β”‚ STACK NAME β”‚ ARTIFACT_STORE β”‚ ORCHESTRATOR ┃ ┠────────┼────────────┼────────────────┼──────────────┨ ┃ πŸ‘‰ β”‚ default β”‚ default β”‚ default ┃ ┗━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛ $ zenml artifact-store describe Running without an active repository root. Using the default local database. Running with active stack: 'default' No component name given; using `default` from active stack. ARTIFACT_STORE Component Configuration (ACTIVE) ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ COMPONENT_PROPERTY β”‚ VALUE ┃ ┠────────────────────┼──────────────────────────────────────────────────────────────────────────────┨ ┃ TYPE β”‚ artifact_store ┃ ┠────────────────────┼──────────────────────────────────────────────────────────────────────────────┨ ┃ FLAVOR β”‚ local ┃ ┠────────────────────┼──────────────────────────────────────────────────────────────────────────────┨ ┃ NAME β”‚ default ┃ ┠────────────────────┼──────────────────────────────────────────────────────────────────────────────┨ ┃ UUID β”‚ 2b7773eb-d371-4f24-96f1-fad15e74fd6e ┃ ┠────────────────────┼──────────────────────────────────────────────────────────────────────────────┨ ┃ PATH β”‚ /home/stefan/.config/zenml/local_stores/2b7773eb-d371-4f24-96f1-fad15e74fd6e ┃ ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` As shown by the `PATH` value in the `zenml artifact-store describe` output, the artifacts are stored inside a folder on your local filesystem. You can create additional instances of local Artifact Stores and use them in your stacks as you see fit, e.g.: ```shell # Register the local artifact store zenml artifact-store register custom_local --flavor local # Register and set a stack with the new artifact store zenml stack register custom_stack -o default -a custom_local --set ``` {% hint style="warning" %} Same as all other Artifact Store flavors, the local Artifact Store does take in a `path` configuration parameter that can be set during registration to point to a custom path on your machine. However, it is highly recommended that you rely on the default `path` value, otherwise, it may lead to unexpected results. Other local stack components depend on the convention used for the default path to be able to access the local Artifact Store. {% endhint %} For more, up-to-date information on the local Artifact Store implementation and its configuration, you can have a look at [the SDK docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-artifact\_stores/#zenml.artifact\_stores.local\_artifact\_store) . ### How do you use it? Aside from the fact that the artifacts are stored locally, using the local Artifact Store is no different from [using any other flavor of Artifact Store](./artifact-stores.md#how-to-use-it).
ZenML Scarf
================ File: docs/book/component-guide/artifact-stores/s3.md ================ --- description: Storing artifacts in an AWS S3 bucket. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Amazon Simple Cloud Storage (S3) The S3 Artifact Store is an [Artifact Store](./artifact-stores.md) flavor provided with the S3 ZenML integration that uses [the AWS S3 managed object storage service](https://aws.amazon.com/s3/) or one of the self-hosted S3 alternatives, such as [MinIO](https://min.io/) or [Ceph RGW](https://ceph.io/en/discover/technology/#object), to store artifacts in an S3 compatible object storage backend. ### When would you want to use it? Running ZenML pipelines with [the local Artifact Store](local.md) is usually sufficient if you just want to evaluate ZenML or get started quickly without incurring the trouble and the cost of employing cloud storage services in your stack. However, the local Artifact Store becomes insufficient or unsuitable if you have more elaborate needs for your project: * if you want to share your pipeline run results with other team members or stakeholders inside or outside your organization * if you have other components in your stack that are running remotely (e.g. a Kubeflow or Kubernetes Orchestrator running in a public cloud). * if you outgrow what your local machine can offer in terms of storage space and need to use some form of private or public storage service that is shared with others * if you are running pipelines at scale and need an Artifact Store that can handle the demands of production-grade MLOps In all these cases, you need an Artifact Store that is backed by a form of public cloud or self-hosted shared object storage service. You should use the S3 Artifact Store when you decide to keep your ZenML artifacts in a shared object storage and if you have access to the AWS S3 managed service or one of the S3 compatible alternatives (e.g. Minio, Ceph RGW). You should consider one of the other [Artifact Store flavors](./artifact-stores.md#artifact-store-flavors) if you don't have access to an S3-compatible service. ### How do you deploy it? {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including an S3 Artifact Store? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), the [stack registration wizard](../../how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md), or [the ZenML AWS Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} The S3 Artifact Store flavor is provided by the S3 ZenML integration, you need to install it on your local machine to be able to register an S3 Artifact Store and add it to your stack: ```shell zenml integration install s3 -y ``` The only configuration parameter mandatory for registering an S3 Artifact Store is the root path URI, which needs to point to an S3 bucket and take the form `s3://bucket-name`. Please read the documentation relevant to the S3 service that you are using on how to create an S3 bucket. For example, the AWS S3 documentation is available [here](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html). With the URI to your S3 bucket known, registering an S3 Artifact Store and using it in a stack can be done as follows: ```shell # Register the S3 artifact-store zenml artifact-store register s3_store -f s3 --path=s3://bucket-name # Register and set a stack with the new artifact store zenml stack register custom_stack -a s3_store ... --set ``` Depending on your use case, however, you may also need to provide additional configuration parameters pertaining to [authentication](s3.md#authentication-methods) or [pass advanced configuration parameters](s3.md#advanced-configuration) to match your S3-compatible service or deployment scenario. #### Authentication Methods Integrating and using an S3-compatible Artifact Store in your pipelines is not possible without employing some form of authentication. If you're looking for a quick way to get started locally, you can use the _Implicit Authentication_ method. However, the recommended way to authenticate to the AWS cloud platform is through [an AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md). This is particularly useful if you are configuring ZenML stacks that combine the S3 Artifact Store with other remote stack components also running in AWS. {% tabs %} {% tab title="Implicit Authentication" %} This method uses the implicit AWS authentication available _in the environment where the ZenML code is running_. On your local machine, this is the quickest way to configure an S3 Artifact Store. You don't need to supply credentials explicitly when you register the S3 Artifact Store, as it leverages the local credentials and configuration that the AWS CLI stores on your local machine. However, you will need to install and set up the AWS CLI on your machine as a prerequisite, as covered in [the AWS CLI documentation](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html), before you register the S3 Artifact Store. {% hint style="warning" %} Certain dashboard functionality, such as visualizing or deleting artifacts, is not available when using an implicitly authenticated artifact store together with a deployed ZenML server because the ZenML server will not have permission to access the filesystem. The implicit authentication method also needs to be coordinated with other stack components that are highly dependent on the Artifact Store and need to interact with it directly to work. If these components are not running on your machine, they do not have access to the local AWS CLI configuration and will encounter authentication failures while trying to access the S3 Artifact Store: * [Orchestrators](../orchestrators/orchestrators.md) need to access the Artifact Store to manage pipeline artifacts * [Step Operators](../step-operators/step-operators.md) need to access the Artifact Store to manage step-level artifacts * [Model Deployers](../model-deployers/model-deployers.md) need to access the Artifact Store to load served models To enable these use-cases, it is recommended to use [an AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md) to link your S3 Artifact Store to the remote S3 bucket. {% endhint %} {% endtab %} {% tab title="AWS Service Connector (recommended)" %} To set up the S3 Artifact Store to authenticate to AWS and access an S3 bucket, it is recommended to leverage the many features provided by [the AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md) such as auto-configuration, best security practices regarding long-lived credentials and fine-grained access control and reusing the same credentials across multiple stack components. If you don't already have an AWS Service Connector configured in your ZenML deployment, you can register one using the interactive CLI command. You have the option to configure an AWS Service Connector that can be used to access more than one S3 bucket or even more than one type of AWS resource: ```sh zenml service-connector register --type aws -i ``` A non-interactive CLI example that leverages [the AWS CLI configuration](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) on your local machine to auto-configure an AWS Service Connector targeting a single S3 bucket is: ```sh zenml service-connector register --type aws --resource-type s3-bucket --resource-name --auto-configure ``` {% code title="Example Command Output" %} ``` $ zenml service-connector register s3-zenfiles --type aws --resource-type s3-bucket --resource-id s3://zenfiles --auto-configure β Έ Registering service connector 's3-zenfiles'... Successfully registered service connector `s3-zenfiles` with access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠───────────────┼────────────────┨ ┃ πŸ“¦ s3-bucket β”‚ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} > **Note**: Please remember to grant the entity associated with your AWS credentials permissions to read and write to your S3 bucket as well as to list accessible S3 buckets. For a full list of permissions required to use an AWS Service Connector to access one or more S3 buckets, please refer to the [AWS Service Connector S3 bucket resource type documentation](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md#s3-bucket) or read the documentation available in the interactive CLI commands and dashboard. The AWS Service Connector supports [many different authentication methods](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md#authentication-methods) with different levels of security and convenience. You should pick the one that best fits your use case. If you already have one or more AWS Service Connectors configured in your ZenML deployment, you can check which of them can be used to access the S3 bucket you want to use for your S3 Artifact Store by running e.g.: ```sh zenml service-connector list-resources --resource-type s3-bucket ``` {% code title="Example Command Output" %} ``` The following 's3-bucket' resources can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼──────────────────────┼────────────────┼───────────────┼────────────────────────────────────────────────┨ ┃ aeed6507-f94c-4329-8bc2-52b85cd8d94d β”‚ aws-s3 β”‚ πŸ”Ά aws β”‚ πŸ“¦ s3-bucket β”‚ s3://zenfiles ┃ ┠──────────────────────────────────────┼──────────────────────┼────────────────┼───────────────┼────────────────────────────────────────────────┨ ┃ 9a810521-ef41-4e45-bb48-8569c5943dc6 β”‚ aws-implicit β”‚ πŸ”Ά aws β”‚ πŸ“¦ s3-bucket β”‚ s3://sagemaker-studio-907999144431-m11qlsdyqr8 ┃ ┃ β”‚ β”‚ β”‚ β”‚ s3://sagemaker-studio-d8a14tvjsmb ┃ ┠──────────────────────────────────────┼──────────────────────┼────────────────┼───────────────┼────────────────────────────────────────────────┨ ┃ 37c97fa0-fa47-4d55-9970-e2aa6e1b50cf β”‚ aws-secret-key β”‚ πŸ”Ά aws β”‚ πŸ“¦ s3-bucket β”‚ s3://zenfiles ┃ ┃ β”‚ β”‚ β”‚ β”‚ s3://zenml-demos ┃ ┃ β”‚ β”‚ β”‚ β”‚ s3://zenml-generative-chat ┃ ┃ β”‚ β”‚ β”‚ β”‚ s3://zenml-public-datasets ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} After having set up or decided on an AWS Service Connector to use to connect to the target S3 bucket, you can register the S3 Artifact Store as follows: ```sh # Register the S3 artifact-store and reference the target S3 bucket zenml artifact-store register -f s3 \ --path='s3://your-bucket' # Connect the S3 artifact-store to the target bucket via an AWS Service Connector zenml artifact-store connect -i ``` A non-interactive version that connects the S3 Artifact Store to a target S3 bucket through an AWS Service Connector: ```sh zenml artifact-store connect --connector ``` {% code title="Example Command Output" %} ``` $ zenml artifact-store connect s3-zenfiles --connector s3-zenfiles Successfully connected artifact store `s3-zenfiles` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────┼────────────────┨ ┃ c4ee3f0a-bc69-4c79-9a74-297b2dd47d50 β”‚ s3-zenfiles β”‚ πŸ”Ά aws β”‚ πŸ“¦ s3-bucket β”‚ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} As a final step, you can use the S3 Artifact Store in a ZenML Stack: ```sh # Register and set a stack with the new artifact store zenml stack register -a ... --set ``` {% endtab %} {% tab title="ZenML Secret" %} When you register the S3 Artifact Store, you can [generate an AWS access key](https://aws.amazon.com/premiumsupport/knowledge-center/create-access-key/), store it in a [ZenML Secret](../../getting-started/deploying-zenml/secret-management.md) and then reference it in the Artifact Store configuration. This method has some advantages over the implicit authentication method: * you don't need to install and configure the AWS CLI on your host * you don't need to care about enabling your other stack components (orchestrators, step operators, and model deployers) to have access to the artifact store through IAM roles and policies * you can combine the S3 artifact store with other stack components that are not running in AWS > **Note**: When you create the IAM user for your AWS access key, please remember to grant the created IAM user permissions to read and write to your S3 bucket (i.e. at a minimum: `s3:PutObject`, `s3:GetObject`, `s3:ListBucket`, `s3:DeleteObject`, `s3:GetBucketVersioning`, `s3:ListBucketVersions`, `s3:DeleteObjectVersion`) After having set up the IAM user and generated the access key, as described in the [AWS documentation](https://aws.amazon.com/premiumsupport/knowledge-center/create-access-key/), you can register the S3 Artifact Store as follows: ```shell # Store the AWS access key in a ZenML secret zenml secret create s3_secret \ --aws_access_key_id='' \ --aws_secret_access_key='' # Register the S3 artifact-store and reference the ZenML secret zenml artifact-store register s3_store -f s3 \ --path='s3://your-bucket' \ --authentication_secret=s3_secret # Register and set a stack with the new artifact store zenml stack register custom_stack -a s3_store ... --set ``` {% endtab %} {% endtabs %} #### Advanced Configuration The S3 Artifact Store accepts a range of advanced configuration options that can be used to further customize how ZenML connects to the S3 storage service that you are using. These are accessible via the `client_kwargs`, `config_kwargs` and `s3_additional_kwargs` configuration attributes and are passed transparently to [the underlying S3Fs library](https://s3fs.readthedocs.io/en/latest/#s3-compatible-storage): * `client_kwargs`: arguments that will be transparently passed to [the botocore client](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html#boto3.session.Session.client) . You can use it to configure parameters like `endpoint_url` and `region_name` when connecting to an S3-compatible endpoint (e.g. Minio). * `config_kwargs`: advanced parameters passed to [botocore.client.Config](https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html). * `s3_additional_kwargs`: advanced parameters that are used when calling S3 API, typically used for things like `ServerSideEncryption` and `ACL`. To include these advanced parameters in your Artifact Store configuration, pass them using JSON format during registration, e.g.: ```shell zenml artifact-store register minio_store -f s3 \ --path='s3://minio_bucket' \ --authentication_secret=s3_secret \ --client_kwargs='{"endpoint_url": "http://minio.cluster.local:9000", "region_name": "us-east-1"}' ``` For more, up-to-date information on the S3 Artifact Store implementation and its configuration, you can have a look at [the SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-s3/#zenml.integrations.s3.artifact\_stores.s3\_artifact\_store) . ### How do you use it? Aside from the fact that the artifacts are stored in an S3 compatible backend, using the S3 Artifact Store is no different than [using any other flavor of Artifact Store](./artifact-stores.md#how-to-use-it).
ZenML Scarf
================ File: docs/book/component-guide/container-registries/aws.md ================ --- description: Storing container images in Amazon ECR. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Amazon Elastic Container Registry (ECR) The AWS container registry is a [container registry](./container-registries.md) flavor provided with the ZenML `aws` integration and uses [Amazon ECR](https://aws.amazon.com/ecr/) to store container images. ### When to use it You should use the AWS container registry if: * one or more components of your stack need to pull or push container images. * you have access to AWS ECR. If you're not using AWS, take a look at the other [container registry flavors](./container-registries.md#container-registry-flavors). ### How to deploy it {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including an AWS ECR container registry? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), the [stack registration wizard](../../how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md), or [the ZenML AWS Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} The ECR registry is automatically activated once you create an AWS account. However, you'll need to create a `Repository` in order to push container images to it: * Go to the [ECR website](https://console.aws.amazon.com/ecr). * Make sure the correct region is selected on the top right. * Click on `Create repository`. * Create a private repository. The name of the repository depends on the [orchestrator](../orchestrators/orchestrators.md) or [step operator](../step-operators/step-operators.md) you're using in your stack. ### URI format The AWS container registry URI should have the following format: ```shell .dkr.ecr..amazonaws.com # Examples: 123456789.dkr.ecr.eu-west-2.amazonaws.com 987654321.dkr.ecr.ap-south-1.amazonaws.com 135792468.dkr.ecr.af-south-1.amazonaws.com ``` To figure out the URI for your registry: * Go to the [AWS console](https://console.aws.amazon.com/) and click on your user account in the top right to see the `Account ID`. * Go [here](https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints) and choose the region in which you would like to store your container images. Make sure to choose a nearby region for faster access. * Once you have both these values, fill in the values in this template `.dkr.ecr..amazonaws.com` to get your container registry URI. ### How to use it To use the AWS container registry, we need: * The ZenML `aws` integration installed. If you haven't done so, run ```shell zenml integration install aws ``` * [Docker](https://www.docker.com) installed and running. * The registry URI. Check out the [previous section](aws.md#how-to-deploy-it) on the URI format and how to get the URI for your registry. We can then register the container registry and use it in our active stack: ```shell zenml container-registry register \ --flavor=aws \ --uri= # Add the container registry to the active stack zenml stack update -c ``` You also need to set up [authentication](aws.md#authentication-methods) required to log in to the container registry. #### Authentication Methods Integrating and using an AWS Container Registry in your pipelines is not possible without employing some form of authentication. If you're looking for a quick way to get started locally, you can use the _Local Authentication_ method. However, the recommended way to authenticate to the AWS cloud platform is through [an AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md). This is particularly useful if you are configuring ZenML stacks that combine the AWS Container Registry with other remote stack components also running in AWS. {% tabs %} {% tab title="Local Authentication" %} This method uses the Docker client authentication available _in the environment where the ZenML code is running_. On your local machine, this is the quickest way to configure an AWS Container Registry. You don't need to supply credentials explicitly when you register the AWS Container Registry, as it leverages the local credentials and configuration that the AWS CLI and Docker client store on your local machine. However, you will need to install and set up the AWS CLI on your machine as a prerequisite, as covered in [the AWS CLI documentation](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html), before you register the AWS Container Registry. With the AWS CLI installed and set up with credentials, we'll need to log in to the container registry so Docker can pull and push images: ```shell # Fill your REGISTRY_URI and REGION in the placeholders in the following command. # You can find the REGION as part of your REGISTRY_URI: `.dkr.ecr..amazonaws.com` aws ecr get-login-password --region | docker login --username AWS --password-stdin ``` {% hint style="warning" %} Stacks using the AWS Container Registry set up with local authentication are not portable across environments. To make ZenML pipelines fully portable, it is recommended to use [an AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md) to link your AWS Container Registry to the remote ECR registry. {% endhint %} {% endtab %} {% tab title="AWS Service Connector (recommended)" %} To set up the AWS Container Registry to authenticate to AWS and access an ECR registry, it is recommended to leverage the many features provided by [the AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md) such as auto-configuration, local login, best security practices regarding long-lived credentials and fine-grained access control and reusing the same credentials across multiple stack components. If you don't already have an AWS Service Connector configured in your ZenML deployment, you can register one using the interactive CLI command. You have the option to configure an AWS Service Connector that can be used to access an ECR registry or even more than one type of AWS resource: ```sh zenml service-connector register --type aws -i ``` A non-interactive CLI example that leverages [the AWS CLI configuration](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) on your local machine to auto-configure an AWS Service Connector targeting an ECR registry is: ```sh zenml service-connector register --type aws --resource-type docker-registry --auto-configure ``` {% code title="Example Command Output" %} ``` $ zenml service-connector register aws-us-east-1 --type aws --resource-type docker-registry --auto-configure β Έ Registering service connector 'aws-us-east-1'... Successfully registered service connector `aws-us-east-1` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry β”‚ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} > **Note**: Please remember to grant the entity associated with your AWS credentials permissions to read and write to one or more ECR repositories as well as to list accessible ECR repositories. For a full list of permissions required to use an AWS Service Connector to access an ECR registry, please refer to the [AWS Service Connector ECR registry resource type documentation](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md#ecr-container-registry) or read the documentation available in the interactive CLI commands and dashboard. The AWS Service Connector supports [many different authentication methods](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md#authentication-methods) with different levels of security and convenience. You should pick the one that best fits your use case. If you already have one or more AWS Service Connectors configured in your ZenML deployment, you can check which of them can be used to access the ECR registry you want to use for your AWS Container Registry by running e.g.: ```sh zenml service-connector list-resources --connector-type aws --resource-type docker-registry ``` {% code title="Example Command Output" %} ``` The following 'docker-registry' resources can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼─────────────────────────┼────────────────┼────────────────────┼──────────────────────────────────────────────┨ ┃ 37c97fa0-fa47-4d55-9970-e2aa6e1b50cf β”‚ aws-secret-key β”‚ πŸ”Ά aws β”‚ 🐳 docker-registry β”‚ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┠──────────────────────────────────────┼─────────────────────────┼────────────────┼────────────────────┼──────────────────────────────────────────────┨ ┃ d400e0c6-a8e7-4b95-ab34-0359229c5d36 β”‚ aws-us-east-1 β”‚ πŸ”Ά aws β”‚ 🐳 docker-registry β”‚ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} After having set up or decided on an AWS Service Connector to use to connect to the target ECR registry, you can register the AWS Container Registry as follows: ```sh # Register the AWS container registry and reference the target ECR registry URI zenml container-registry register -f aws \ --uri= # Connect the AWS container registry to the target ECR registry via an AWS Service Connector zenml container-registry connect -i ``` A non-interactive version that connects the AWS Container Registry to a target ECR registry through an AWS Service Connector: ```sh zenml container-registry connect --connector ``` {% code title="Example Command Output" %} ``` $ zenml container-registry connect aws-us-east-1 --connector aws-us-east-1 Successfully connected container registry `aws-us-east-1` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────────┼──────────────────────────────────────────────┨ ┃ d400e0c6-a8e7-4b95-ab34-0359229c5d36 β”‚ aws-us-east-1 β”‚ πŸ”Ά aws β”‚ 🐳 docker-registry β”‚ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} As a final step, you can use the AWS Container Registry in a ZenML Stack: ```sh # Register and set a stack with the new container registry zenml stack register -c ... --set ``` {% hint style="info" %} Linking the AWS Container Registry to a Service Connector means that your local Docker client is no longer authenticated to access the remote registry. If you need to manually interact with the remote registry via the Docker CLI, you can use the [local login Service Connector feature](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md#configure-local-clients) to temporarily authenticate your local Docker client to the remote registry: ```sh zenml service-connector login --resource-type docker-registry ``` {% code title="Example Command Output" %} ``` $ zenml service-connector login aws-us-east-1 --resource-type docker-registry β Ό Attempting to configure local client using service connector 'aws-us-east-1'... WARNING! Your password will be stored unencrypted in /home/stefan/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store The 'aws-us-east-1' Docker Service Connector connector was used to successfully configure the local Docker/OCI container registry client/SDK. ``` {% endcode %} {% endhint %} {% endtab %} {% endtabs %} For more information and a full list of configurable attributes of the AWS container registry, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-aws/#zenml.integrations.aws.container\_registries.aws\_container\_registry.AWSContainerRegistry).
ZenML Scarf
================ File: docs/book/component-guide/container-registries/azure.md ================ --- description: Storing container images in Azure. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Azure Container Registry The Azure container registry is a [container registry](./container-registries.md) flavor that comes built-in with ZenML and uses the [Azure Container Registry](https://azure.microsoft.com/en-us/services/container-registry/) to store container images. ### When to use it You should use the Azure container registry if: * one or more components of your stack need to pull or push container images. * you have access to Azure. If you're not using Azure, take a look at the other [container registry flavors](./container-registries.md#container-registry-flavors). ### How to deploy it {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including an Azure container registry? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), the [stack registration wizard](../../how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md), or [the ZenML Azure Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} Go [here](https://portal.azure.com/#create/Microsoft.ContainerRegistry) and choose a subscription, resource group, location, and registry name. Then click on `Review + Create` and to create your container registry. ### How to find the registry URI The Azure container registry URI should have the following format: ```shell .azurecr.io # Examples: zenmlregistry.azurecr.io myregistry.azurecr.io ``` To figure out the URI for your registry: * Go to the [Azure portal](https://portal.azure.com/#home). * In the search bar, enter `container registries` and select the container registry you want to use. If you don't have any container registries yet, check out the [deployment section](azure.md#how-to-deploy-it) on how to create one. * Use the name of your registry to fill the template `.azurecr.io` and get your URI. ### How to use it To use the Azure container registry, we need: * [Docker](https://www.docker.com) installed and running. * The registry URI. Check out the [previous section](azure.md#how-to-find-the-registry-uri) on the URI format and how to get the URI for your registry. We can then register the container registry and use it in our active stack: ```shell zenml container-registry register \ --flavor=azure \ --uri= # Add the container registry to the active stack zenml stack update -c ``` You also need to set up [authentication](azure.md#authentication-methods) required to log in to the container registry. #### Authentication Methods Integrating and using an Azure Container Registry in your pipelines is not possible without employing some form of authentication. If you're looking for a quick way to get started locally, you can use the _Local Authentication_ method. However, the recommended way to authenticate to the Azure cloud platform is through [an Azure Service Connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md). This is particularly useful if you are configuring ZenML stacks that combine the Azure Container Registry with other remote stack components also running in Azure. {% tabs %} {% tab title="Local Authentication" %} This method uses the Docker client authentication available _in the environment where the ZenML code is running_. On your local machine, this is the quickest way to configure an Azure Container Registry. You don't need to supply credentials explicitly when you register the Azure Container Registry, as it leverages the local credentials and configuration that the Azure CLI and Docker client store on your local machine. However, you will need to install and set up the Azure CLI on your machine as a prerequisite, as covered in [the Azure CLI documentation](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli), before you register the Azure Container Registry. With the Azure CLI installed and set up with credentials, you need to login to the container registry so Docker can pull and push images: ```shell # Fill your REGISTRY_NAME in the placeholder in the following command. # You can find the REGISTRY_NAME as part of your registry URI: `.azurecr.io` az acr login --name= ``` {% hint style="warning" %} Stacks using the Azure Container Registry set up with local authentication are not portable across environments. To make ZenML pipelines fully portable, it is recommended to use [an Azure Service Connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md) to link your Azure Container Registry to the remote ACR registry. {% endhint %} {% endtab %} {% tab title="Azure Service Connector (recommended)" %} To set up the Azure Container Registry to authenticate to Azure and access an ACR registry, it is recommended to leverage the many features provided by [the Azure Service Connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md) such as auto-configuration, local login, best security practices regarding long-lived credentials and reusing the same credentials across multiple stack components. If you don't already have an Azure Service Connector configured in your ZenML deployment, you can register one using the interactive CLI command. You have the option to configure an Azure Service Connector that can be used to access a ACR registry or even more than one type of Azure resource: ```sh zenml service-connector register --type azure -i ``` A non-interactive CLI example that uses [Azure Service Principal credentials](https://learn.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals) to configure an Azure Service Connector targeting a single ACR registry is: ```sh zenml service-connector register --type azure --auth-method service-principal --tenant_id= --client_id= --client_secret= --resource-type docker-registry --resource-id ``` {% code title="Example Command Output" %} ``` $ zenml service-connector register azure-demo --type azure --auth-method service-principal --tenant_id=a79f3633-8f45-4a74-a42e-68871c17b7fb --client_id=8926254a-8c3f-430a-a2fd-bdab234d491e --client_secret=AzureSuperSecret --resource-type docker-registry --resource-id demozenmlcontainerregistry.azurecr.io β Έ Registering service connector 'azure-demo'... Successfully registered service connector `azure-demo` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠────────────────────┼───────────────────────────────────────┨ ┃ 🐳 docker-registry β”‚ demozenmlcontainerregistry.azurecr.io ┃ ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} > **Note**: Please remember to grant the entity associated with your Azure credentials permissions to read and write to your ACR registry as well as to list accessible ACR registries. For a full list of permissions required to use an Azure Service Connector to access a ACR registry, please refer to the [Azure Service Connector ACR registry resource type documentation](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md#acr-container-registry) or read the documentation available in the interactive CLI commands and dashboard. The Azure Service Connector supports [many different authentication methods](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md#authentication-methods) with different levels of security and convenience. You should pick the one that best fits your use case. If you already have one or more Azure Service Connectors configured in your ZenML deployment, you can check which of them can be used to access the ACR registry you want to use for your Azure Container Registry by running e.g.: ```sh zenml service-connector list-resources --connector-type azure --resource-type docker-registry ``` {% code title="Example Command Output" %} ``` The following 'docker-registry' resources can be accessed by 'azure' service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────────┼───────────────────────────────────────┨ ┃ db5821d0-a658-4504-ae96-04c3302d8f85 β”‚ azure-demo β”‚ πŸ‡¦ azure β”‚ 🐳 docker-registry β”‚ demozenmlcontainerregistry.azurecr.io ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} After having set up or decided on an Azure Service Connector to use to connect to the target ACR registry, you can register the Azure Container Registry as follows: ```sh # Register the Azure container registry and reference the target ACR registry URI zenml container-registry register -f azure \ --uri= # Connect the Azure container registry to the target ACR registry via an Azure Service Connector zenml container-registry connect -i ``` A non-interactive version that connects the Azure Container Registry to a target ACR registry through an Azure Service Connector: ```sh zenml container-registry connect --connector ``` {% code title="Example Command Output" %} ``` $ zenml container-registry connect azure-demo --connector azure-demo Successfully connected container registry `azure-demo` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────────┼───────────────────────────────────────┨ ┃ db5821d0-a658-4504-ae96-04c3302d8f85 β”‚ azure-demo β”‚ πŸ‡¦ azure β”‚ 🐳 docker-registry β”‚ demozenmlcontainerregistry.azurecr.io ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} As a final step, you can use the Azure Container Registry in a ZenML Stack: ```sh # Register and set a stack with the new container registry zenml stack register -c ... --set ``` {% hint style="info" %} Linking the Azure Container Registry to a Service Connector means that your local Docker client is no longer authenticated to access the remote registry. If you need to manually interact with the remote registry via the Docker CLI, you can use the [local login Service Connector feature](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md#configure-local-clients) to temporarily authenticate your local Docker client to the remote registry: ```sh zenml service-connector login --resource-type docker-registry --resource-id ``` {% code title="Example Command Output" %} ``` $ zenml service-connector login azure-demo --resource-type docker-registry --resource-id demozenmlcontainerregistry.azurecr.io β Ή Attempting to configure local client using service connector 'azure-demo'... WARNING! Your password will be stored unencrypted in /home/stefan/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store The 'azure-demo' Docker Service Connector connector was used to successfully configure the local Docker/OCI container registry client/SDK. ``` {% endcode %} {% endhint %} {% endtab %} {% endtabs %} For more information and a full list of configurable attributes of the Azure container registry, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-container\_registries/#zenml.container\_registries.azure\_container\_registry.AzureContainerRegistry) .
ZenML Scarf
================ File: docs/book/component-guide/container-registries/container-registries.md ================ --- icon: box description: Setting up a storage for Docker images. --- # Container Registries The container registry is an essential part of most remote MLOps stacks. It is used to store container images that are built to run machine learning pipelines in remote environments. Containerization of the pipeline code creates a portable environment that allows code to run in an isolated manner. ### When to use it The container registry is needed whenever other components of your stack need to push or pull container images. Currently, this is the case for most of ZenML's remote [orchestrators](../orchestrators/orchestrators.md) , [step operators](../step-operators/step-operators.md), and some [model deployers](../model-deployers/model-deployers.md). These containerize your pipeline code and therefore require a container registry to store the resulting [Docker](https://www.docker.com/) images. Take a look at the documentation page of the component you want to use in your stack to see if it requires a container registry or even a specific container registry flavor. ### Container Registry Flavors ZenML comes with a few container registry flavors that you can use: * Default flavor: Allows any URI without validation. Use this if you want to use a local container registry or when using a remote container registry that is not covered by other flavors. * Specific flavors: Validates your container registry URI and performs additional checks to ensure you're able to push to the registry. {% hint style="warning" %} We highly suggest using the specific container registry flavors in favor of the `default` one to make use of the additional URI validations. {% endhint %} | Container Registry | Flavor | Integration | URI example | |--------------------------------------------|-------------|-------------|-------------------------------------------| | [DefaultContainerRegistry](default.md) | `default` | _built-in_ | - | | [DockerHubContainerRegistry](dockerhub.md) | `dockerhub` | _built-in_ | docker.io/zenml | | [GCPContainerRegistry](gcp.md) | `gcp` | _built-in_ | gcr.io/zenml | | [AzureContainerRegistry](azure.md) | `azure` | _built-in_ | zenml.azurecr.io | | [GitHubContainerRegistry](github.md) | `github` | _built-in_ | ghcr.io/zenml | | [AWSContainerRegistry](aws.md) | `aws` | `aws` | 123456789.dkr.ecr.us-east-1.amazonaws.com | If you would like to see the available flavors of container registries, you can use the command: ```shell zenml container-registry flavor list ```
ZenML Scarf
================ File: docs/book/component-guide/container-registries/custom.md ================ --- description: Learning how to develop a custom container registry. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a custom container registry {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} ### Base Abstraction In the current version of ZenML, container registries have a rather basic base abstraction. In essence, their base configuration only features a `uri` and their implementation features a non-abstract `prepare_image_push` method for validation. ```python from abc import abstractmethod from typing import Type from zenml.enums import StackComponentType from zenml.stack import Flavor from zenml.stack.authentication_mixin import ( AuthenticationConfigMixin, AuthenticationMixin, ) from zenml.utils import docker_utils class BaseContainerRegistryConfig(AuthenticationConfigMixin): """Base config for a container registry.""" uri: str class BaseContainerRegistry(AuthenticationMixin): """Base class for all ZenML container registries.""" def prepare_image_push(self, image_name: str) -> None: """Conduct necessary checks/preparations before an image gets pushed.""" def push_image(self, image_name: str) -> str: """Pushes a Docker image.""" if not image_name.startswith(self.config.uri): raise ValueError( f"Docker image `{image_name}` does not belong to container " f"registry `{self.config.uri}`." ) self.prepare_image_push(image_name) return docker_utils.push_image(image_name) class BaseContainerRegistryFlavor(Flavor): """Base flavor for container registries.""" @property @abstractmethod def name(self) -> str: """Returns the name of the flavor.""" @property def type(self) -> StackComponentType: """Returns the flavor type.""" return StackComponentType.CONTAINER_REGISTRY @property def config_class(self) -> Type[BaseContainerRegistryConfig]: """Config class for this flavor.""" return BaseContainerRegistryConfig @property def implementation_class(self) -> Type[BaseContainerRegistry]: """Implementation class.""" return BaseContainerRegistry ``` {% hint style="info" %} This is a slimmed-down version of the base implementation which aims to highlight the abstraction layer. In order to see the full implementation and get the complete docstrings, please check the [SDK docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-container\_registries/#zenml.container\_registries.base\_container\_registry.BaseContainerRegistry) . {% endhint %} ### Building your own container registry If you want to create your own custom flavor for a container registry, you can follow the following steps: 1. Create a class that inherits from the `BaseContainerRegistry` class and if you need to execute any checks/validation before the image gets pushed, you can define these operations in the `prepare_image_push` method. As an example, you can check the `AWSContainerRegistry`. 2. If you need further configuration, you can create a class which inherits from the `BaseContainerRegistryConfig` class. 3. Bring both the implementation and the configuration together by inheriting from the `BaseContainerRegistryFlavor` class. Once you are done with the implementation, you can register it through the CLI. Please ensure you **point to the flavor class via dot notation**: ```shell zenml container-registry flavor register ``` For example, your flavor class `MyContainerRegistryFlavor` is defined in `flavors/my_flavor.py`, you'd register it by doing: ```shell zenml container-registry flavor register flavors.my_flavor.MyContainerRegistryFlavor ``` {% hint style="warning" %} ZenML resolves the flavor class by taking the path where you initialized zenml (via `zenml init`) as the starting point of resolution. Therefore, please ensure you follow [the best practice](../../how-to/infrastructure-deployment/infrastructure-as-code/best-practices.md) of initializing zenml at the root of your repository. If ZenML does not find an initialized ZenML repository in any parent directory, it will default to the current working directory, but usually it's better to not have to rely on this mechanism, and initialize zenml at the root. {% endhint %} Afterward, you should see the new flavor in the list of available flavors: ```shell zenml container-registry flavor list ``` {% hint style="warning" %} It is important to draw attention to when and how these base abstractions are coming into play in a ZenML workflow. * The **CustomContainerRegistryFlavor** class is imported and utilized upon the creation of the custom flavor through the CLI. * The **CustomContainerRegistryConfig** class is imported when someone tries to register/update a stack component with this custom flavor. Especially, during the registration process of the stack component, the config will be used to validate the values given by the user. As `Config` object are inherently `pydantic` objects, you can also add your own custom validators here. * The **CustomContainerRegistry** only comes into play when the component is ultimately in use. The design behind this interaction lets us separate the configuration of the flavor from its implementation. This way we can register flavors and components even when the major dependencies behind their implementation are not installed in our local setting (assuming the `CustomContainerRegistryFlavor` and the `CustomContainerRegistryConfig` are implemented in a different module/path than the actual `CustomContainerRegistry`). {% endhint %}
ZenML Scarf
================ File: docs/book/component-guide/container-registries/default.md ================ --- description: Storing container images locally. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Default Container Registry The Default container registry is a [container registry](./container-registries.md) flavor that comes built-in with ZenML and allows container registry URIs of any format. ### When to use it You should use the Default container registry if you want to use a **local** container registry or when using a remote container registry that is not covered by other [container registry flavors](./container-registries.md#container-registry-flavors). ### Local registry URI format To specify a URI for a local container registry, use the following format: ```shell localhost: # Examples: localhost:5000 localhost:8000 localhost:9999 ``` ### How to use it To use the Default container registry, we need: * [Docker](https://www.docker.com) installed and running. * The registry URI. If you're using a local container registry, check out * the [previous section](default.md#local-registry-uri-format) on the URI format. We can then register the container registry and use it in our active stack: ```shell zenml container-registry register \ --flavor=default \ --uri= # Add the container registry to the active stack zenml stack update -c ``` You may also need to set up [authentication](default.md#authentication-methods) required to log in to the container registry. #### Authentication Methods If you are using a private container registry, you will need to configure some form of authentication to login to the registry. If you're looking for a quick way to get started locally, you can use the _Local Authentication_ method. However, the recommended way to authenticate to a remote private container registry is through [a Docker Service Connector](../../how-to/infrastructure-deployment/auth-management/docker-service-connector.md). If your target private container registry comes from a cloud provider like AWS, GCP or Azure, you should use the [container registry flavor](./container-registries.md#container-registry-flavors) targeted at that cloud provider. For example, if you're using AWS, you should use the [AWS Container Registry](aws.md) flavor. These cloud provider flavors also use specialized cloud provider Service Connectors to authenticate to the container registry. {% tabs %} {% tab title="Local Authentication" %} This method uses the Docker client authentication available _in the environment where the ZenML code is running_. On your local machine, this is the quickest way to configure a Default Container Registry. You don't need to supply credentials explicitly when you register the Default Container Registry, as it leverages the local credentials and configuration that the Docker client stores on your local machine. To log in to the container registry so Docker can pull and push images, you'll need to run the `docker login` command and supply your credentials, e.g.: ```shell docker login --username --password-stdin ``` {% hint style="warning" %} Stacks using the Default Container Registry set up with local authentication are not portable across environments. To make ZenML pipelines fully portable, it is recommended to use [a Docker Service Connector](../../how-to/infrastructure-deployment/auth-management/docker-service-connector.md) to link your Default Container Registry to the remote private container registry. {% endhint %} {% endtab %} {% tab title="Docker Service Connector (recommended)" %} To set up the Default Container Registry to authenticate to and access a private container registry, it is recommended to leverage the features provided by [the Docker Service Connector](../../how-to/infrastructure-deployment/auth-management/docker-service-connector.md) such as local login and reusing the same credentials across multiple stack components. If you don't already have a Docker Service Connector configured in your ZenML deployment, you can register one using the interactive CLI command: ```sh zenml service-connector register --type docker -i ``` A non-interactive CLI example is: ```sh zenml service-connector register --type docker --username= --password= ``` {% code title="Example Command Output" %} ``` $ zenml service-connector register dockerhub --type docker --username=username --password=password Successfully registered service connector `dockerhub` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠────────────────────┼────────────────┨ ┃ 🐳 docker-registry β”‚ docker.io ┃ ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} If you already have one or more Docker Service Connectors configured in your ZenML deployment, you can check which of them can be used to access the container registry you want to use for your Default Container Registry by running e.g.: ```sh zenml service-connector list-resources --connector-type docker --resource-id ``` {% code title="Example Command Output" %} ``` $ zenml service-connector list-resources --connector-type docker --resource-id docker.io The resource with name 'docker.io' can be accessed by 'docker' service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────────┼────────────────┨ ┃ cf55339f-dbc8-4ee6-862e-c25aff411292 β”‚ dockerhub β”‚ 🐳 docker β”‚ 🐳 docker-registry β”‚ docker.io ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} After having set up or decided on a Docker Service Connector to use to connect to the target container registry, you can register the Docker Container Registry as follows: ```sh # Register the container registry and reference the target registry URI zenml container-registry register -f default \ --uri= # Connect the container registry to the target registry via a Docker Service Connector zenml container-registry connect -i ``` A non-interactive version that connects the Default Container Registry to a target registry through a Docker Service Connector: ```sh zenml container-registry connect --connector ``` {% code title="Example Command Output" %} ``` $ zenml container-registry connect dockerhub --connector dockerhub Successfully connected container registry `dockerhub` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────────┼────────────────┨ ┃ cf55339f-dbc8-4ee6-862e-c25aff411292 β”‚ dockerhub β”‚ 🐳 docker β”‚ 🐳 docker-registry β”‚ docker.io ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} As a final step, you can use the Default Container Registry in a ZenML Stack: ```sh # Register and set a stack with the new container registry zenml stack register -c ... --set ``` {% hint style="info" %} Linking the Default Container Registry to a Service Connector means that your local Docker client is no longer authenticated to access the remote registry. If you need to manually interact with the remote registry via the Docker CLI, you can use the [local login Service Connector feature](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md#configure-local-clients) to temporarily authenticate your local Docker client to the remote registry: ```sh zenml service-connector login ``` {% code title="Example Command Output" %} ``` $ zenml service-connector login dockerhub β Ή Attempting to configure local client using service connector 'dockerhub'... WARNING! Your password will be stored unencrypted in /home/stefan/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store The 'dockerhub' Docker Service Connector connector was used to successfully configure the local Docker/OCI container registry client/SDK. ``` {% endcode %} {% endhint %} {% endtab %} {% endtabs %} For more information and a full list of configurable attributes of the Default container registry, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-aws/#zenml.integrations.aws.container\_registries.default\_container\_registry.DefaultContainerRegistry) .
ZenML Scarf
================ File: docs/book/component-guide/container-registries/dockerhub.md ================ --- description: Storing container images in DockerHub. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # DockerHub The DockerHub container registry is a [container registry](./container-registries.md) flavor that comes built-in with ZenML and uses [DockerHub](https://hub.docker.com/) to store container images. ### When to use it You should use the DockerHub container registry if: * one or more components of your stack need to pull or push container images. * you have a DockerHub account. If you're not using DockerHub, take a look at the other [container registry flavors](./container-registries.md#container-registry-flavors). ### How to deploy it To use the DockerHub container registry, all you need to do is create a [DockerHub](https://hub.docker.com/) account. When this container registry is used in a ZenML stack, the Docker images that are built will be published in a \*\* public\*\* repository and everyone will be able to pull your images. If you want to use a **private** repository instead, you'll have to [create a private repository](https://docs.docker.com/docker-hub/repos/#creating-repositories) on the website before running the pipeline. The repository name depends on the remote [orchestrator](../orchestrators/orchestrators.md) or [step operator](../step-operators/step-operators.md) that you're using in your stack. ### How to find the registry URI The DockerHub container registry URI should have one of the two following formats: ```shell # or docker.io/ # Examples: zenml my-username docker.io/zenml docker.io/my-username ``` To figure out the URI for your registry: * Find out the account name of your [DockerHub](https://hub.docker.com/) account. * Use the account name to fill the template `docker.io/` and get your URI. ### How to use it To use the Azure container registry, we need: * [Docker](https://www.docker.com) installed and running. * The registry URI. Check out the [previous section](dockerhub.md#how-to-find-the-registry-uri) on the URI format and how to get the URI for your registry. We can then register the container registry and use it in our active stack: ```shell zenml container-registry register \ --flavor=dockerhub \ --uri= # Add the container registry to the active stack zenml stack update -c ``` Additionally, we'll need to log in to the container registry so Docker can pull and push images. This will require your DockerHub account name and either your password or preferably a [personal access token](https://docs.docker.com/docker-hub/access-tokens/). ```shell docker login ``` For more information and a full list of configurable attributes of the `dockerhub` container registry, check out the [SDK Docs](https://apidocs.zenml.io/latest/core\_code\_docs/core-container\_registries/#zenml.container\_registries.dockerhub\_container\_registry.DockerHubContainerRegistry) .
ZenML Scarf
================ File: docs/book/component-guide/container-registries/gcp.md ================ --- description: Storing container images in GCP. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Google Cloud Container Registry The GCP container registry is a [container registry](./container-registries.md) flavor that comes built-in with ZenML and uses the [Google Artifact Registry](https://cloud.google.com/artifact-registry). {% hint style="warning" %} **Important Notice: Google Container Registry** [**is being replaced by Artifact Registry**](https://cloud.google.com/artifact-registry/docs/transition/transition-from-gcr)**. Please start using Artifact Registry for your containers. As per Google's documentation, "after May 15, 2024, Artifact Registry will host images for the gcr.io domain in Google Cloud projects without previous Container Registry usage. After March 18, 2025, Container Registry will be shut down."** The terms `container registry` and `artifact registry` will be used interchangeably throughout this document. {% endhint %} ### When to use it You should use the GCP container registry if: * one or more components of your stack need to pull or push container images. * you have access to GCP. If you're not using GCP, take a look at the other [container registry flavors](./container-registries.md#container-registry-flavors). ### How to deploy it {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including a Google Artifact Registry? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), the [stack registration wizard](../../how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md), or [the ZenML GCP Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} When using the Google Artifact Registry, you need to: * enable it [here](https://console.cloud.google.com/marketplace/product/google/artifactregistry.googleapis.com) * go [here](https://console.cloud.google.com/artifacts) and create a `Docker` repository. ## How to find the registry URI When using the Google Artifact Registry, the GCP container registry URI should have the following format: ```shell -docker.pkg.dev// # Examples: europe-west1-docker.pkg.dev/zenml/my-repo southamerica-east1-docker.pkg.dev/zenml/zenml-test asia-docker.pkg.dev/my-project/another-repo ``` To figure out the URI for your registry: * Go [here](https://console.cloud.google.com/artifacts) and select the repository that you want to use to store Docker images. If you don't have a repository yet, take a look at the [deployment section](gcp.md#how-to-deploy-it). * On the top, click the copy button to copy the full repository URL. ### How to use it To use the GCP container registry, we need: * [Docker](https://www.docker.com) installed and running. * The registry URI. Check out the [previous section](gcp.md#how-to-find-the-registry-uri) on the URI format and how to get the URI for your registry. We can then register the container registry and use it in our active stack: ```shell zenml container-registry register \ --flavor=gcp \ --uri= # Add the container registry to the active stack zenml stack update -c ``` You also need to set up [authentication](gcp.md#authentication-methods) required to log in to the container registry. #### Authentication Methods Integrating and using a GCP Container Registry in your pipelines is not possible without employing some form of authentication. If you're looking for a quick way to get started locally, you can use the _Local Authentication_ method. However, the recommended way to authenticate to the GCP cloud platform is through [a GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md). This is particularly useful if you are configuring ZenML stacks that combine the GCP Container Registry with other remote stack components also running in GCP. {% tabs %} {% tab title="Local Authentication" %} This method uses the Docker client authentication available _in the environment where the ZenML code is running_. On your local machine, this is the quickest way to configure a GCP Container Registry. You don't need to supply credentials explicitly when you register the GCP Container Registry, as it leverages the local credentials and configuration that the GCP CLI and Docker client store on your local machine. However, you will need to install and set up the GCP CLI on your machine as a prerequisite, as covered in [the GCP CLI documentation](https://cloud.google.com/sdk/docs/install-sdk), before you register the GCP Container Registry. With the GCP CLI installed and set up with credentials, we'll need to configure Docker, so it can pull and push images: * for a Google Container Registry: ```shell gcloud auth configure-docker ``` * for a Google Artifact Registry: ```shell gcloud auth configure-docker -docker.pkg.dev ``` {% hint style="warning" %} Stacks using the GCP Container Registry set up with local authentication are not portable across environments. To make ZenML pipelines fully portable, it is recommended to use [a GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) to link your GCP Container Registry to the remote GCR registry. {% endhint %} {% endtab %} {% tab title="GCP Service Connector (recommended)" %} To set up the GCP Container Registry to authenticate to GCP and access a GCR registry, it is recommended to leverage the many features provided by [the GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) such as auto-configuration, local login, best security practices regarding long-lived credentials and reusing the same credentials across multiple stack components. {% hint style="warning" %} The GCP Service Connector does not support the Google Artifact Registry yet. If you need to connect your GCP Container Registry to a Google Artifact Registry, you can use the _Local Authentication_ method instead. {% endhint %} If you don't already have a GCP Service Connector configured in your ZenML deployment, you can register one using the interactive CLI command. You have the option to configure a GCP Service Connector that can be used to access a GCR registry or even more than one type of GCP resource: ```sh zenml service-connector register --type gcp -i ``` A non-interactive CLI example that leverages [the GCP CLI configuration](https://docs.gcp.amazon.com/cli/latest/userguide/getting-started-install.html) on your local machine to auto-configure a GCP Service Connector targeting a GCR registry is: ```sh zenml service-connector register --type gcp --resource-type docker-registry --auto-configure ``` {% code title="Example Command Output" %} ``` $ zenml service-connector register gcp-zenml-core --type gcp --resource-type docker-registry --auto-configure β Έ Registering service connector 'gcp-zenml-core'... Successfully registered service connector `gcp-zenml-core` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠────────────────────┼─────────────────────────────────────────────────┨ ┃ 🐳 docker-registry β”‚ gcr.io/zenml-core ┃ ┃ β”‚ us.gcr.io/zenml-core ┃ ┃ β”‚ eu.gcr.io/zenml-core ┃ ┃ β”‚ asia.gcr.io/zenml-core ┃ ┃ β”‚ asia-docker.pkg.dev/zenml-core/asia.gcr.io ┃ ┃ β”‚ europe-docker.pkg.dev/zenml-core/eu.gcr.io ┃ ┃ β”‚ europe-west1-docker.pkg.dev/zenml-core/test ┃ ┃ β”‚ us-docker.pkg.dev/zenml-core/gcr.io ┃ ┃ β”‚ us-docker.pkg.dev/zenml-core/us.gcr.io ┃ ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} > **Note**: Please remember to grant the entity associated with your GCP credentials permissions to read and write to your GCR registry. For a full list of permissions required to use a GCP Service Connector to access a GCR registry, please refer to the [GCP Service Connector GCR registry resource type documentation](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md#gcr-container-registry) or read the documentation available in the interactive CLI commands and dashboard. The GCP Service Connector supports [many different authentication methods](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md#authentication-methods) with different levels of security and convenience. You should pick the one that best fits your use-case. If you already have one or more GCP Service Connectors configured in your ZenML deployment, you can check which of them can be used to access the GCR registry you want to use for your GCP Container Registry by running e.g.: ```sh zenml service-connector list-resources --connector-type gcp --resource-type docker-registry ``` {% code title="Example Command Output" %} ```text The following 'docker-registry' resources can be accessed by 'gcp' service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼──────────────────┼────────────────┼────────────────────┼─────────────────────────────────────────────────┨ ┃ ffc01795-0c0a-4f1d-af80-b84aceabcfcf β”‚ gcp-implicit β”‚ πŸ”΅ gcp β”‚ 🐳 docker-registry β”‚ gcr.io/zenml-core ┃ ┃ β”‚ β”‚ β”‚ β”‚ us.gcr.io/zenml-core ┃ ┃ β”‚ β”‚ β”‚ β”‚ eu.gcr.io/zenml-core ┃ ┃ β”‚ β”‚ β”‚ β”‚ asia.gcr.io/zenml-core ┃ ┃ β”‚ β”‚ β”‚ β”‚ asia-docker.pkg.dev/zenml-core/asia.gcr.io ┃ ┃ β”‚ β”‚ β”‚ β”‚ europe-docker.pkg.dev/zenml-core/eu.gcr.io ┃ ┃ β”‚ β”‚ β”‚ β”‚ europe-west1-docker.pkg.dev/zenml-core/test ┃ ┃ β”‚ β”‚ β”‚ β”‚ us-docker.pkg.dev/zenml-core/gcr.io ┃ ┃ β”‚ β”‚ β”‚ β”‚ us-docker.pkg.dev/zenml-core/us.gcr.io ┃ ┠──────────────────────────────────────┼──────────────────┼────────────────┼────────────────────┼─────────────────────────────────────────────────┨ ┃ 561b776a-af8b-491c-a4ed-14349b440f30 β”‚ gcp-zenml-core β”‚ πŸ”΅ gcp β”‚ 🐳 docker-registry β”‚ gcr.io/zenml-core ┃ ┃ β”‚ β”‚ β”‚ β”‚ us.gcr.io/zenml-core ┃ ┃ β”‚ β”‚ β”‚ β”‚ eu.gcr.io/zenml-core ┃ ┃ β”‚ β”‚ β”‚ β”‚ asia.gcr.io/zenml-core ┃ ┃ β”‚ β”‚ β”‚ β”‚ asia-docker.pkg.dev/zenml-core/asia.gcr.io ┃ ┃ β”‚ β”‚ β”‚ β”‚ europe-docker.pkg.dev/zenml-core/eu.gcr.io ┃ ┃ β”‚ β”‚ β”‚ β”‚ europe-west1-docker.pkg.dev/zenml-core/test ┃ ┃ β”‚ β”‚ β”‚ β”‚ us-docker.pkg.dev/zenml-core/gcr.io ┃ ┃ β”‚ β”‚ β”‚ β”‚ us-docker.pkg.dev/zenml-core/us.gcr.io ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} After having set up or decided on a GCP Service Connector to use to connect to the target GCR registry, you can register the GCP Container Registry as follows: ```sh # Register the GCP container registry and reference the target GCR registry URI zenml container-registry register -f gcp \ --uri= # Connect the GCP container registry to the target GCR registry via a GCP Service Connector zenml container-registry connect -i ``` A non-interactive version that connects the GCP Container Registry to a target GCR registry through a GCP Service Connector: ```sh zenml container-registry connect --connector ``` {% hint style="info" %} Linking the GCP Container Registry to a Service Connector means that your local Docker client is no longer authenticated to access the remote registry. If you need to manually interact with the remote registry via the Docker CLI, you can use the [local login Service Connector feature](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md#configure-local-clients) to temporarily authenticate your local Docker client to the remote registry: ```sh zenml service-connector login --resource-type docker-registry ``` {% code title="Example Command Output" %} ```text $ zenml service-connector login gcp-zenml-core --resource-type docker-registry β ‹ Attempting to configure local client using service connector 'gcp-zenml-core'... WARNING! Your password will be stored unencrypted in /home/stefan/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store The 'gcp-zenml-core' Docker Service Connector connector was used to successfully configure the local Docker/OCI container registry client/SDK. ``` {% endcode %} {% endhint %} {% code title="Example Command Output" %} ```text $ zenml container-registry connect gcp-zenml-core --connector gcp-zenml-core Successfully connected container registry `gcp-zenml-core` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────────┼─────────────────────────────────────────────┨ ┃ 561b776a-af8b-491c-a4ed-14349b440f30 β”‚ gcp-zenml-core β”‚ πŸ”΅ gcp β”‚ 🐳 docker-registry β”‚ europe-west1-docker.pkg.dev/zenml-core/test ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} As a final step, you can use the GCP Container Registry in a ZenML Stack: ```sh # Register and set a stack with the new container registry zenml stack register -c ... --set ``` {% endtab %} {% endtabs %} For more information and a full list of configurable attributes of the GCP container registry, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-container\_registries/#zenml.container\_registries.gcp\_container\_registry.GCPContainerRegistry) .
ZenML Scarf
================ File: docs/book/component-guide/container-registries/github.md ================ --- description: Storing container images in GitHub. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # GitHub Container Registry The GitHub container registry is a [container registry](./container-registries.md) flavor that comes built-in with ZenML and uses the [GitHub Container Registry](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry) to store container images. ### When to use it You should use the GitHub container registry if: * one or more components of your stack need to pull or push container images. * you're using GitHub for your projects. If you're not using GitHub, take a look at the other [container registry flavors](./container-registries.md#container-registry-flavors). ### How to deploy it The GitHub container registry is enabled by default when you create a GitHub account. ### How to find the registry URI The GitHub container registry URI should have the following format: ```shell ghcr.io/ # Examples: ghcr.io/zenml ghcr.io/my-username ghcr.io/my-organization ``` To figure our the URI for your registry: * Use the GitHub user or organization name to fill the template `ghcr.io/` and get your URI. ### How to use it To use the GitHub container registry, we need: * [Docker](https://www.docker.com) installed and running. * The registry URI. Check out the [previous section](github.md#how-to-find-the-registry-uri) on the URI format and how to get the URI for your registry. * Our Docker client configured, so it can pull and push images. Follow [this guide](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#authenticating-to-the-container-registry) to create a personal access token and login to the container registry. We can then register the container registry and use it in our active stack: ```shell zenml container-registry register \ --flavor=github \ --uri= # Add the container registry to the active stack zenml stack update -c ``` For more information and a full list of configurable attributes of the GitHub container registry, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-container\_registries/#zenml.container\_registries.github\_container\_registry.GitHubContainerRegistry) .
ZenML Scarf
================ File: docs/book/component-guide/data-validators/custom.md ================ --- description: How to develop a custom data validator --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a custom data validator {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} {% hint style="warning" %} **Base abstraction in progress!** We are actively working on the base abstraction for the Data Validators, which will be available soon. As a result, their extension is not recommended at the moment. When you are selecting a data validator for your stack, you can use one of [the existing flavors](./data-validators.md#data-validator-flavors). If you need to implement your own Data Validator flavor, you can still do so, but keep in mind that you may have to refactor it when the base abstraction is updated. {% endhint %} ZenML comes equipped with [Data Validator implementations](./data-validators.md#data-validator-flavors) that integrate a variety of data logging and validation libraries, frameworks and platforms. However, if you need to use a different library or service as a backend for your ZenML Data Validator, you can extend ZenML to provide your own custom Data Validator implementation. ### Build your own custom data validator If you want to implement your own custom Data Validator, you can follow the following steps: 1. Create a class which inherits from [the `BaseDataValidator` class](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-data\_validators/#zenml.data\_validators.base\_data\_validator.BaseDataValidator) and override one or more of the abstract methods, depending on the capabilities of the underlying library/service that you want to integrate. 2. If you need any configuration, you can create a class which inherits from the `BaseDataValidatorConfig` class. 3. Bring both of these classes together by inheriting from the `BaseDataValidatorFlavor`. 4. (Optional) You should also provide some standard steps that others can easily insert into their pipelines for instant access to data validation features. Once you are done with the implementation, you can register it through the CLI. Please ensure you **point to the flavor class via dot notation**: ```shell zenml data-validator flavor register ``` For example, if your flavor class `MyDataValidatorFlavor` is defined in `flavors/my_flavor.py`, you'd register it by doing: ```shell zenml data-validator flavor register flavors.my_flavor.MyDataValidatorFlavor ``` {% hint style="warning" %} ZenML resolves the flavor class by taking the path where you initialized zenml (via `zenml init`) as the starting point of resolution. Therefore, please ensure you follow [the best practice](../../how-to/infrastructure-deployment/infrastructure-as-code/best-practices.md) of initializing zenml at the root of your repository. If ZenML does not find an initialized ZenML repository in any parent directory, it will default to the current working directory, but usually it's better to not have to rely on this mechanism, and initialize zenml at the root. {% endhint %} Afterwards, you should see the new flavor in the list of available flavors: ```shell zenml data-validator flavor list ``` {% hint style="warning" %} It is important to draw attention to when and how these base abstractions are coming into play in a ZenML workflow. * The **CustomDataValidatorFlavor** class is imported and utilized upon the creation of the custom flavor through the CLI. * The **CustomDataValidatorConfig** class is imported when someone tries to register/update a stack component with this custom flavor. Especially, during the registration process of the stack component, the config will be used to validate the values given by the user. As `Config` object are inherently `pydantic` objects, you can also add your own custom validators here. * The **CustomDataValidator** only comes into play when the component is ultimately in use. The design behind this interaction lets us separate the configuration of the flavor from its implementation. This way we can register flavors and components even when the major dependencies behind their implementation are not installed in our local setting (assuming the `CustomDataValidatorFlavor` and the `CustomDataValidatorConfig` are implemented in a different module/path than the actual `CustomDataValidator`). {% endhint %}
ZenML Scarf
================ File: docs/book/component-guide/data-validators/data-validators.md ================ --- icon: chart-column description: >- How to enhance and maintain the quality of your data and the performance of your models with data profiling and validation --- # Data Validators Without good data, even the best machine learning models will yield questionable results. A lot of effort goes into ensuring and maintaining data quality not only in the initial stages of model development, but throughout the entire machine learning project lifecycle. Data Validators are a category of ML libraries, tools and frameworks that grant a wide range of features and best practices that should be employed in the ML pipelines to keep data quality in check and to monitor model performance to keep it from degrading over time. Data profiling, data integrity testing, data and model drift detection are all ways of employing data validation techniques at different points in your ML pipelines where data is concerned: data ingestion, model training and evaluation and online or batch inference. Data profiles and model performance evaluation results can be visualized and analyzed to detect problems and take preventive or correcting actions. Related concepts: * the Data Validator is an optional type of Stack Component that needs to be registered as part of your ZenML [Stack](../../user-guide/production-guide/understand-stacks.md). * Data Validators used in ZenML pipelines usually generate data profiles and data quality check reports that are versioned and stored in the [Artifact Store](../artifact-stores/artifact-stores.md) and can be [retrieved and visualized](../../how-to/data-artifact-management/visualize-artifacts/README.md) later. ### When to use it [Data-centric AI practices](https://blog.zenml.io/data-centric-mlops/) are quickly becoming mainstream and using Data Validators are an easy way to incorporate them into your workflow. These are some common cases where you may consider employing the use of Data Validators in your pipelines: * early on, even if it's just to keep a log of the quality state of your data and the performance of your models at different stages of development. * if you have pipelines that regularly ingest new data, you should use data validation to run regular data integrity checks to signal problems before they are propagated downstream. * in continuous training pipelines, you should use data validation techniques to compare new training data against a data reference and to compare the performance of newly trained models against previous ones. * when you have pipelines that automate batch inference or if you regularly collect data used as input in online inference, you should use data validation to run data drift analyzes and detect training-serving skew, data drift and model drift. #### Data Validator Flavors Data Validator are optional stack components provided by integrations. The following table lists the currently available Data Validators and summarizes their features and the data types and model types that they can be used with in ZenML pipelines: | Data Validator | Validation Features | Data Types | Model Types | Notes | Flavor/Integration | | ------------------------------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -------------------- | | [Deepchecks](deepchecks.md) |

data quality
data drift
model drift
model performance

|

tabular: pandas.DataFrame
CV: torch.utils.data.dataloader.DataLoader

|

tabular: sklearn.base.ClassifierMixin
CV: torch.nn.Module

| Add Deepchecks data and model validation tests to your pipelines | `deepchecks` | | [Evidently](evidently.md) |

data quality
data drift
model drift
model performance

| tabular: `pandas.DataFrame` | N/A | Use Evidently to generate a variety of data quality and data/model drift reports and visualizations | `evidently` | | [Great Expectations](great-expectations.md) |

data profiling
data quality

| tabular: `pandas.DataFrame` | N/A | Perform data testing, documentation and profiling with Great Expectations | `great_expectations` | | [Whylogs/WhyLabs](whylogs.md) | data drift | tabular: `pandas.DataFrame` | N/A | Generate data profiles with whylogs and upload them to WhyLabs | `whylogs` | If you would like to see the available flavors of Data Validator, you can use the command: ```shell zenml data-validator flavor list ``` ### How to use it Every Data Validator has different data profiling and testing capabilities and uses a slightly different way of analyzing your data and your models, but it generally works as follows: * first, you have to configure and add a Data Validator to your ZenML stack * every integration includes one or more builtin data validation steps that you can add to your pipelines. Of course, you can also use the libraries directly in your own custom pipeline steps and simply return the results (e.g. data profiles, test reports) as artifacts that are versioned and stored by ZenML in its Artifact Store. * you can access the data validation artifacts in subsequent pipeline steps, or [fetch them afterwards](../../how-to/data-artifact-management/handle-data-artifacts/load-artifacts-into-memory.md) to process them or visualize them as needed. Consult the documentation for the particular [Data Validator flavor](data-validators.md#data-validator-flavors) that you plan on using or are using in your stack for detailed information about how to use it in your ZenML pipelines.
ZenML Scarf
================ File: docs/book/component-guide/data-validators/deepchecks.md ================ --- description: >- How to test the data and models used in your pipelines with Deepchecks test suites --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Deepchecks The Deepchecks [Data Validator](./data-validators.md) flavor provided with the ZenML integration uses [Deepchecks](https://deepchecks.com/) to run data integrity, data drift, model drift and model performance tests on the datasets and models circulated in your ZenML pipelines. The test results can be used to implement automated corrective actions in your pipelines or to render interactive representations for further visual interpretation, evaluation and documentation. ### When would you want to use it? [Deepchecks](https://deepchecks.com/) is an open-source library that you can use to run a variety of data and model validation tests, from data integrity tests that work with a single dataset to model evaluation tests to data drift analyzes and model performance comparison tests. All this can be done with minimal configuration input from the user, or customized with specialized conditions that the validation tests should perform. Deepchecks works with both tabular data and computer vision data. For tabular, the supported dataset format is `pandas.DataFrame` and the supported model format is `sklearn.base.ClassifierMixin`. For computer vision, the supported dataset format is `torch.utils.data.dataloader.DataLoader` and supported model format is `torch.nn.Module`. You should use the Deepchecks Data Validator when you need the following data and/or model validation features that are possible with Deepchecks: * Data Integrity Checks [for tabular](https://docs.deepchecks.com/stable/tabular/auto_checks/data_integrity/index.html) or [computer vision](https://docs.deepchecks.com/stable/vision/auto_checks/data_integrity/index.html) data: detect data integrity problems within a single dataset (e.g. missing values, conflicting labels, mixed data types etc.). * Data Drift Checks [for tabular](https://docs.deepchecks.com/stable/tabular/auto_checks/train_test_validation/index.html) or [computer vision](https://docs.deepchecks.com/stable/vision/auto_checks/train_test_validation/index.html) data: detect data skew and data drift problems by comparing a target dataset against a reference dataset (e.g. feature drift, label drift, new labels etc.). * Model Performance Checks [for tabular](https://docs.deepchecks.com/stable/tabular/auto_checks/model_evaluation/index.html) or [computer vision](https://docs.deepchecks.com/stable/vision/auto_checks/model_evaluation/index.html) data: evaluate a model and detect problems with its performance (e.g. confusion matrix, boosting overfit, model error analysis) * Multi-Model Performance Reports [for tabular](https://docs.deepchecks.com/stable/tabular/auto_checks/model_evaluation/plot_multi_model_performance_report.html#sphx-glr-tabular-auto-checks-model-evaluation-plot-multi-model-performance-report-py): produce a summary of performance scores for multiple models on test datasets. You should consider one of the other [Data Validator flavors](./data-validators.md#data-validator-flavors) if you need a different set of data validation features. ### How do you deploy it? The Deepchecks Data Validator flavor is included in the Deepchecks ZenML integration, you need to install it on your local machine to be able to register a Deepchecks Data Validator and add it to your stack: ```shell zenml integration install deepchecks -y ``` The Data Validator stack component does not have any configuration parameters. Adding it to a stack is as simple as running e.g.: ```shell # Register the Deepchecks data validator zenml data-validator register deepchecks_data_validator --flavor=deepchecks # Register and set a stack with the new data validator zenml stack register custom_stack -dv deepchecks_data_validator ... --set ``` ### How do you use it? The ZenML integration restructures the way Deepchecks validation checks are organized in four categories, based on the type and number of input parameters that they expect as input. This makes it easier to reason about them when you decide which tests to use in your pipeline steps: * **data integrity checks** expect a single dataset as input. These correspond one-to-one to the set of Deepchecks data integrity checks [for tabular](https://docs.deepchecks.com/stable/tabular/auto_checks/data_integrity/index.html) and [computer vision](https://docs.deepchecks.com/stable/vision/auto_checks/data_integrity/index.html) data * **data drift checks** require two datasets as input: target and reference. These correspond one-to-one to the set of Deepchecks train-test checks [for tabular data](https://docs.deepchecks.com/stable/tabular/auto_checks/train_test_validation/index.html) and [for computer vision](https://docs.deepchecks.com/stable/vision/auto_checks/train_test_validation/index.html). * **model validation checks** require a single dataset and a mandatory model as input. This list includes a subset of the model evaluation checks provided by Deepchecks [for tabular data](https://docs.deepchecks.com/stable/tabular/auto_checks/model_evaluation/index.html) and [for computer vision](https://docs.deepchecks.com/stable/vision/auto_checks/model_evaluation/index.html) that expect a single dataset as input. * **model drift checks** require two datasets and a mandatory model as input. This list includes a subset of the model evaluation checks provided by Deepchecks [for tabular data](https://docs.deepchecks.com/stable/tabular/auto_checks/model_evaluation/index.html) and [for computer vision](https://docs.deepchecks.com/stable/vision/auto_checks/model_evaluation/index.html) that expect two datasets as input: target and reference. This structure is directly reflected in how Deepchecks can be used with ZenML: there are four different Deepchecks standard steps and four different [ZenML enums for Deepchecks checks](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-deepchecks/#zenml.integrations.deepchecks.validation\_checks) . [The Deepchecks Data Validator API](deepchecks.md#the-deepchecks-data-validator) is also modeled to reflect this same structure. A notable characteristic of Deepchecks is that you don't need to customize the set of Deepchecks tests that are part of a test suite. Both ZenML and Deepchecks provide sane defaults that will run all available Deepchecks tests in a given category with their default conditions if a custom list of tests and conditions are not provided. There are three ways you can use Deepchecks in your ZenML pipelines that allow different levels of flexibility: * instantiate, configure and insert one or more of [the standard Deepchecks steps](deepchecks.md#the-deepchecks-standard-steps) shipped with ZenML into your pipelines. This is the easiest way and the recommended approach, but can only be customized through the supported step configuration parameters. * call the data validation methods provided by [the Deepchecks Data Validator](deepchecks.md#the-deepchecks-data-validator) in your custom step implementation. This method allows for more flexibility concerning what can happen in the pipeline step, but you are still limited to the functionality implemented in the Data Validator. * [use the Deepchecks library directly](deepchecks.md#call-deepchecks-directly) in your custom step implementation. This gives you complete freedom in how you are using Deepchecks' features. You can visualize Deepchecks results in Jupyter notebooks or view them directly in the ZenML dashboard. ### Warning! Usage in remote orchestrators The current ZenML version has a limitation in its base Docker image that requires a workaround for _all_ pipelines using Deepchecks with a remote orchestrator (e.g. [Kubeflow](../orchestrators/kubeflow.md) , [Vertex](../orchestrators/vertex.md)). The limitation being that the base Docker image needs to be extended to include binaries that are required by `opencv2`, which is a package that Deepchecks requires. While these binaries might be available on most operating systems out of the box (and therefore not a problem with the default local orchestrator), we need to tell ZenML to add them to the containerization step when running in remote settings. Here is how: First, create a file called `deepchecks-zenml.Dockerfile` and place it on the same level as your runner script (commonly called `run.py`). The contents of the Dockerfile are as follows: ```shell ARG ZENML_VERSION=0.20.0 FROM zenmldocker/zenml:${ZENML_VERSION} AS base RUN apt-get update RUN apt-get install ffmpeg libsm6 libxext6 -y ``` Then, place the following snippet above your pipeline definition. Note that the path of the `dockerfile` are relative to where the pipeline definition file is. Read [the containerization guide](../../how-to/customize-docker-builds/README.md) for more details: ```python import zenml from zenml import pipeline from zenml.config import DockerSettings from pathlib import Path import sys docker_settings = DockerSettings( dockerfile="deepchecks-zenml.Dockerfile", build_options={ "buildargs": { "ZENML_VERSION": f"{zenml.__version__}" }, }, ) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): # same code as always ... ``` From here on, you can continue to use the deepchecks integration as is explained below. #### The Deepchecks standard steps ZenML wraps the Deepchecks functionality for tabular data in the form of four standard steps: * [`deepchecks_data_integrity_check_step`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-deepchecks/#zenml.integrations.deepchecks.steps.deepchecks_data_integrity): use it in your pipelines to run data integrity tests on a single dataset * [`deepchecks_data_drift_check_step`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-deepchecks/#zenml.integrations.deepchecks.steps.deepchecks_data_drift): use it in your pipelines to run data drift tests on two datasets as input: target and reference. * [`deepchecks_model_validation_check_step`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-deepchecks/#zenml.integrations.deepchecks.steps.deepchecks_model_validation): use it in your pipelines to run model performance tests using a single dataset and a mandatory model artifact as input * [`deepchecks_model_drift_check_step`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-deepchecks/#zenml.integrations.deepchecks.steps.deepchecks_model_drift): use it in your pipelines to run model comparison/drift tests using a mandatory model artifact and two datasets as input: target and reference. The integration doesn't yet include standard steps for computer vision, but you can still write your own custom steps that call [the Deepchecks Data Validator API](deepchecks.md#the-deepchecks-data-validator) or even [call the Deepchecks library directly](deepchecks.md#call-deepchecks-directly). All four standard steps behave similarly regarding the configuration parameters and returned artifacts, with the following differences: * the type and number of input artifacts are different, as mentioned above * each step expects a different enum data type to be used when explicitly listing the checks to be performed via the `check_list` configuration attribute. See the [`zenml.integrations.deepchecks.validation_checks`](https://sdkdocs.zenml.io/0.66.0/integration_code_docs/integrations-deepchecks/#zenml.integrations.deepchecks.validation_checks) module for more details about these enums (e.g. the data integrity step expects a list of `DeepchecksDataIntegrityCheck` values). This section will only cover how you can use the data integrity step, with a similar usage to be easily inferred for the other three steps. To instantiate a data integrity step that will run all available Deepchecks data integrity tests with their default configuration, e.g.: ```python from zenml.integrations.deepchecks.steps import ( deepchecks_data_integrity_check_step, ) data_validator = deepchecks_data_integrity_check_step.with_options( parameters=dict( dataset_kwargs=dict(label="target", cat_features=[]), ), ) ``` The step can then be inserted into your pipeline where it can take in a dataset, e.g.: ```python docker_settings = DockerSettings(required_integrations=[DEEPCHECKS, SKLEARN]) @pipeline(settings={"docker": docker_settings}) def data_validation_pipeline(): df_train, df_test = data_loader() data_validator(dataset=df_train) data_validation_pipeline() ``` As can be seen from the [step definition](https://sdkdocs.zenml.io/0.66.0/integration_code_docs/integrations-deepchecks/#zenml.integrations.deepchecks.steps.deepchecks_data_integrity) , the step takes in a dataset and it returns a Deepchecks `SuiteResult` object that contains the test results: ```python @step def deepchecks_data_integrity_check_step( dataset: pd.DataFrame, check_list: Optional[Sequence[DeepchecksDataIntegrityCheck]] = None, dataset_kwargs: Optional[Dict[str, Any]] = None, check_kwargs: Optional[Dict[str, Any]] = None, run_kwargs: Optional[Dict[str, Any]] = None, ) -> SuiteResult: ... ``` If needed, you can specify a custom list of data integrity Deepchecks tests to be executed by supplying a `check_list` argument: ```python from zenml.integrations.deepchecks.validation_checks import DeepchecksDataIntegrityCheck from zenml.integrations.deepchecks.steps import deepchecks_data_integrity_check_step @pipeline def validation_pipeline(): deepchecks_data_integrity_check_step( check_list=[ DeepchecksDataIntegrityCheck.TABULAR_MIXED_DATA_TYPES, DeepchecksDataIntegrityCheck.TABULAR_DATA_DUPLICATES, DeepchecksDataIntegrityCheck.TABULAR_CONFLICTING_LABELS, ], dataset=... ) ``` You should consult [the official Deepchecks documentation](https://docs.deepchecks.com/stable/tabular/auto_checks/data_integrity/index.html) for more information on what each test is useful for. For more customization, the data integrity step also allows for additional keyword arguments to be supplied to be passed transparently to the Deepchecks library: * `dataset_kwargs`: Additional keyword arguments to be passed to the Deepchecks `tabular.Dataset` or `vision.VisionData` constructor. This is used to pass additional information about how the data is structured, e.g.: ```python deepchecks_data_integrity_check_step( dataset_kwargs=dict(label='class', cat_features=['country', 'state']), ... ) ``` * `check_kwargs`: Additional keyword arguments to be passed to the Deepchecks check object constructors. Arguments are grouped for each check and indexed using the full check class name or check enum value as dictionary keys, e.g.: ```python deepchecks_data_integrity_check_step( check_list=[ DeepchecksDataIntegrityCheck.TABULAR_OUTLIER_SAMPLE_DETECTION, DeepchecksDataIntegrityCheck.TABULAR_STRING_LENGTH_OUT_OF_BOUNDS, DeepchecksDataIntegrityCheck.TABULAR_STRING_MISMATCH, ], check_kwargs={ DeepchecksDataIntegrityCheck.TABULAR_OUTLIER_SAMPLE_DETECTION: dict( nearest_neighbors_percent=0.01, extent_parameter=3, ), DeepchecksDataIntegrityCheck.TABULAR_STRING_LENGTH_OUT_OF_BOUNDS: dict( num_percentiles=1000, min_unique_values=3, ), }, ... ) ``` * `run_kwargs`: Additional keyword arguments to be passed to the Deepchecks Suite `run` method. The `check_kwargs` attribute can also be used to customize [the conditions](https://docs.deepchecks.com/stable/general/usage/customizations/auto_examples/plot_configure_check_conditions.html#configure-check-conditions) configured for each Deepchecks test. ZenML attaches a special meaning to all check arguments that start with `condition_` and have a dictionary as value. This is required because there is no declarative way to specify conditions for Deepchecks checks. For example, the following step configuration: ```python deepchecks_data_integrity_check_step( check_list=[ DeepchecksDataIntegrityCheck.TABULAR_OUTLIER_SAMPLE_DETECTION, DeepchecksDataIntegrityCheck.TABULAR_STRING_LENGTH_OUT_OF_BOUNDS, ], dataset_kwargs=dict(label='class', cat_features=['country', 'state']), check_kwargs={ DeepchecksDataIntegrityCheck.TABULAR_OUTLIER_SAMPLE_DETECTION: dict( nearest_neighbors_percent=0.01, extent_parameter=3, condition_outlier_ratio_less_or_equal=dict( max_outliers_ratio=0.007, outlier_score_threshold=0.5, ), condition_no_outliers=dict( outlier_score_threshold=0.6, ) ), DeepchecksDataIntegrityCheck.TABULAR_STRING_LENGTH_OUT_OF_BOUNDS: dict( num_percentiles=1000, min_unique_values=3, condition_number_of_outliers_less_or_equal=dict( max_outliers=3, ) ), }, ... ) ``` is equivalent to running the following Deepchecks tests: ```python import deepchecks.tabular.checks as tabular_checks from deepchecks.tabular import Suite from deepchecks.tabular import Dataset train_dataset = Dataset( reference_dataset, label='class', cat_features=['country', 'state'] ) suite = Suite(name="custom") check = tabular_checks.OutlierSampleDetection( nearest_neighbors_percent=0.01, extent_parameter=3, ) check.add_condition_outlier_ratio_less_or_equal( max_outliers_ratio=0.007, outlier_score_threshold=0.5, ) check.add_condition_no_outliers( outlier_score_threshold=0.6, ) suite.add(check) check = tabular_checks.StringLengthOutOfBounds( num_percentiles=1000, min_unique_values=3, ) check.add_condition_number_of_outliers_less_or_equal( max_outliers=3, ) suite.run(train_dataset=train_dataset) ``` #### The Deepchecks Data Validator The Deepchecks Data Validator implements the same interface as do all Data Validators, so this method forces you to maintain some level of compatibility with the overall Data Validator abstraction, which guarantees an easier migration in case you decide to switch to another Data Validator. All you have to do is call the Deepchecks Data Validator methods when you need to interact with Deepchecks to run tests, e.g.: ```python import pandas as pd from deepchecks.core.suite import SuiteResult from zenml.integrations.deepchecks.data_validators import DeepchecksDataValidator from zenml.integrations.deepchecks.validation_checks import DeepchecksDataIntegrityCheck from zenml import step @step def data_integrity_check( dataset: pd.DataFrame, ) -> SuiteResult: """Custom data integrity check step with Deepchecks Args: dataset: input Pandas DataFrame Returns: Deepchecks test suite execution result """ # validation pre-processing (e.g. dataset preparation) can take place here data_validator = DeepchecksDataValidator.get_active_data_validator() suite = data_validator.data_validation( dataset=dataset, check_list=[ DeepchecksDataIntegrityCheck.TABULAR_OUTLIER_SAMPLE_DETECTION, DeepchecksDataIntegrityCheck.TABULAR_STRING_LENGTH_OUT_OF_BOUNDS, ], ) # validation post-processing (e.g. interpret results, take actions) can happen here return suite ``` The arguments that the Deepchecks Data Validator methods can take in are the same as those used for [the Deepchecks standard steps](deepchecks.md#the-deepchecks-standard-steps). Have a look at [the complete list of methods and parameters available in the `DeepchecksDataValidator` API](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-deepchecks/#zenml.integrations.deepchecks.data_validators.deepchecks_data_validator.DeepchecksDataValidator) in the SDK docs. #### Call Deepchecks directly You can use the Deepchecks library directly in your custom pipeline steps, and only leverage ZenML's capability of serializing, versioning and storing the `SuiteResult` objects in its Artifact Store, e.g.: ```python import pandas as pd import deepchecks.tabular.checks as tabular_checks from deepchecks.core.suite import SuiteResult from deepchecks.tabular import Suite from deepchecks.tabular import Dataset from zenml import step @step def data_integrity_check( dataset: pd.DataFrame, ) -> SuiteResult: """Custom data integrity check step with Deepchecks Args: dataset: a Pandas DataFrame Returns: Deepchecks test suite execution result """ # validation pre-processing (e.g. dataset preparation) can take place here train_dataset = Dataset( dataset, label='class', cat_features=['country', 'state'] ) suite = Suite(name="custom") check = tabular_checks.OutlierSampleDetection( nearest_neighbors_percent=0.01, extent_parameter=3, ) check.add_condition_outlier_ratio_less_or_equal( max_outliers_ratio=0.007, outlier_score_threshold=0.5, ) suite.add(check) check = tabular_checks.StringLengthOutOfBounds( num_percentiles=1000, min_unique_values=3, ) check.add_condition_number_of_outliers_less_or_equal( max_outliers=3, ) results = suite.run(train_dataset=train_dataset) # validation post-processing (e.g. interpret results, take actions) can happen here return results ``` #### Visualizing Deepchecks Suite Results You can view visualizations of the suites and results generated by your pipeline steps directly in the ZenML dashboard by clicking on the respective artifact in the pipeline run DAG. Alternatively, if you are running inside a Jupyter notebook, you can load and render the suites and results using the [artifact.visualize() method](../../how-to/data-artifact-management/visualize-artifacts/README.md), e.g.: ```python from zenml.client import Client def visualize_results(pipeline_name: str, step_name: str) -> None: pipeline = Client().get_pipeline(pipeline=pipeline_name) last_run = pipeline.last_run step = last_run.steps[step_name] step.visualize() if __name__ == "__main__": visualize_results("data_validation_pipeline", "data_integrity_check") ```
ZenML Scarf
================ File: docs/book/component-guide/data-validators/evidently.md ================ --- description: >- How to keep your data quality in check and guard against data and model drift with Evidently profiling --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Evidently The Evidently [Data Validator](./data-validators.md) flavor provided with the ZenML integration uses [Evidently](https://evidentlyai.com/) to perform data quality, data drift, model drift and model performance analyzes, to generate reports and run checks. The reports and check results can be used to implement automated corrective actions in your pipelines or to render interactive representations for further visual interpretation, evaluation and documentation. ### When would you want to use it? [Evidently](https://evidentlyai.com/) is an open-source library that you can use to monitor and debug machine learning models by analyzing the data that they use through a powerful set of data profiling and visualization features, or to run a variety of data and model validation reports and tests, from data integrity tests that work with a single dataset to model evaluation tests to data drift analysis and model performance comparison tests. All this can be done with minimal configuration input from the user, or customized with specialized conditions that the validation tests should perform. Evidently currently works with tabular data in `pandas.DataFrame` or CSV file formats and can handle both regression and classification tasks. You should use the Evidently Data Validator when you need the following data and/or model validation features that are possible with Evidently: * [Data Quality](https://docs.evidentlyai.com/presets/data-quality) reports and tests: provides detailed feature statistics and a feature behavior overview for a single dataset. It can also compare any two datasets. E.g. you can use it to compare train and test data, reference and current data, or two subgroups of one dataset. * [Data Drift](https://docs.evidentlyai.com/presets/data-drift) reports and tests: helps detects and explore feature distribution changes in the input data by comparing two datasets with identical schema. * [Target Drift](https://docs.evidentlyai.com/presets/target-drift) reports and tests: helps detect and explore changes in the target function and/or model predictions by comparing two datasets where the target and/or prediction columns are available. * [Regression Performance](https://docs.evidentlyai.com/presets/reg-performance) or [Classification Performance](https://docs.evidentlyai.com/presets/class-performance) reports and tests: evaluate the performance of a model by analyzing a single dataset where both the target and prediction columns are available. It can also compare it to the past performance of the same model, or the performance of an alternative model by providing a second dataset. You should consider one of the other [Data Validator flavors](./data-validators.md#data-validator-flavors) if you need a different set of data validation features. ### How do you deploy it? The Evidently Data Validator flavor is included in the Evidently ZenML integration, you need to install it on your local machine to be able to register an Evidently Data Validator and add it to your stack: ```shell zenml integration install evidently -y ``` The Data Validator stack component does not have any configuration parameters. Adding it to a stack is as simple as running e.g.: ```shell # Register the Evidently data validator zenml data-validator register evidently_data_validator --flavor=evidently # Register and set a stack with the new data validator zenml stack register custom_stack -dv evidently_data_validator ... --set ``` ### How do you use it? #### Data Profiling Evidently's profiling functions take in a `pandas.DataFrame` dataset or a pair of datasets and generate results in the form of a `Report` object. One of Evidently's notable characteristics is that it only requires datasets as input. Even when running model performance comparison analyzes, no model needs to be present. However, that does mean that the input data needs to include additional `target` and `prediction` columns for some profiling reports and, you have to include additional information about the dataset columns in the form of [column mappings](https://docs.evidentlyai.com/user-guide/tests-and-reports/column-mapping). Depending on how your data is structured, you may also need to include additional steps in your pipeline before the data validation step to insert the additional `target` and `prediction` columns into your data. This may also require interacting with one or more models. There are three ways you can use Evidently to generate data reports in your ZenML pipelines that allow different levels of flexibility: * instantiate, configure and insert the standard Evidently report step shipped with ZenML into your pipelines. This is the easiest way and the recommended approach. * call the data validation methods provided by [the Evidently Data Validator](evidently.md#the-evidently-data-validator) in your custom step implementation. This method allows for more flexibility concerning what can happen in the pipeline step. * [use the Evidently library directly](evidently.md#call-evidently-directly) in your custom step implementation. This gives you complete freedom in how you are using Evidently's features. You can [visualize Evidently reports](evidently.md#visualizing-evidently-reports) in Jupyter notebooks or view them directly in the ZenML dashboard by clicking on the respective artifact in the pipeline run DAG. **The Evidently Report step** ZenML wraps the Evidently data profiling functionality in the form of a standard Evidently report pipeline step that you can simply instantiate and insert in your pipeline. Here you can see how instantiating and configuring the standard Evidently report step can be done: ```python from zenml.integrations.evidently.metrics import EvidentlyMetricConfig from zenml.integrations.evidently.steps import ( EvidentlyColumnMapping, evidently_report_step, ) text_data_report = evidently_report_step.with_options( parameters=dict( column_mapping=EvidentlyColumnMapping( target="Rating", numerical_features=["Age", "Positive_Feedback_Count"], categorical_features=[ "Division_Name", "Department_Name", "Class_Name", ], text_features=["Review_Text", "Title"], ), metrics=[ EvidentlyMetricConfig.metric("DataQualityPreset"), EvidentlyMetricConfig.metric( "TextOverviewPreset", column_name="Review_Text" ), EvidentlyMetricConfig.metric_generator( "ColumnRegExpMetric", columns=["Review_Text", "Title"], reg_exp=r"[A-Z][A-Za-z0-9 ]*", ), ], # We need to download the NLTK data for the TextOverviewPreset download_nltk_data=True, ), ) ``` The configuration shown in the example is the equivalent of running the following Evidently code inside the step: ```python from evidently.metrics import ColumnRegExpMetric from evidently.metric_preset import DataQualityPreset, TextOverviewPreset from evidently import ColumnMapping from evidently.report import Report from evidently.metrics.base_metric import generate_column_metrics import nltk nltk.download("words") nltk.download("wordnet") nltk.download("omw-1.4") column_mapping = ColumnMapping( target="Rating", numerical_features=["Age", "Positive_Feedback_Count"], categorical_features=[ "Division_Name", "Department_Name", "Class_Name", ], text_features=["Review_Text", "Title"], ) report = Report( metrics=[ DataQualityPreset(), TextOverviewPreset(column_name="Review_Text"), generate_column_metrics( ColumnRegExpMetric, columns=["Review_Text", "Title"], parameters={"reg_exp": r"[A-Z][A-Za-z0-9 ]*"} ) ] ) # The datasets are those that are passed to the Evidently step # as input artifacts report.run( current_data=current_dataset, reference_data=reference_dataset, column_mapping=column_mapping, ) ``` Let's break this down... We configure the `evidently_report_step` using parameters that you would normally pass to the Evidently `Report` object to [configure and run an Evidently report](https://docs.evidentlyai.com/user-guide/tests-and-reports/custom-report). It consists of the following fields: * `column_mapping`: This is an `EvidentlyColumnMapping` object that is the exact equivalent of [the `ColumnMapping` object in Evidently](https://docs.evidentlyai.com/user-guide/input-data/column-mapping). It is used to describe the columns in the dataset and how they should be treated (e.g. as categorical, numerical, or text features). * `metrics`: This is a list of `EvidentlyMetricConfig` objects that are used to configure the metrics that should be used to generate the report in a declarative way. This is the same as configuring the `metrics` that go in the Evidently `Report`. * `download_nltk_data`: This is a boolean that is used to indicate whether the NLTK data should be downloaded. This is only needed if you are using Evidently reports that handle text data, which require the NLTK data to be downloaded ahead of time. There are several ways you can reference the Evidently metrics when configuring `EvidentlyMetricConfig` items: * by class name: this is the easiest way to reference an Evidently metric. You can use the name of a metric or metric preset class as it appears in the Evidently documentation (e.g.`"DataQualityPreset"`, `"DatasetDriftMetric"`). * by full class path: you can also use the full Python class path of the metric or metric preset class ( e.g. `"evidently.metric_preset.DataQualityPreset"`, `"evidently.metrics.DatasetDriftMetric"`). This is useful if you want to use metrics or metric presets that are not included in Evidently library. * by passing in the class itself: you can also import and pass in an Evidently metric or metric preset class itself, e.g.: ```python from evidently.metrics import DatasetDriftMetric ... evidently_report_step.with_options( parameters=dict( metrics=[EvidentlyMetricConfig.metric(DatasetDriftMetric)] ), ) ``` As can be seen in the example, there are two basic ways of adding metrics to your Evidently report step configuration: * to add a single metric or metric preset: call `EvidentlyMetricConfig.metric` with an Evidently metric or metric preset class name (or class path or class). The rest of the parameters are the same ones that you would usually pass to the Evidently metric or metric preset class constructor. * to generate multiple metrics, similar to calling [the Evidently column metric generator](https://docs.evidentlyai.com/user-guide/tests-and-reports/test-metric-generator#column-metric-generator): call `EvidentlyMetricConfig.metric_generator` with an Evidently metric or metric preset class name (or class path or class) and a list of column names. The rest of the parameters are the same ones that you would usually pass to the Evidently metric or metric preset class constructor. The ZenML Evidently report step can then be inserted into your pipeline where it can take in two datasets and outputs the Evidently report generated in both JSON and HTML formats, e.g.: ```python @pipeline(enable_cache=False, settings={"docker": docker_settings}) def text_data_report_test_pipeline(): """Links all the steps together in a pipeline.""" data = data_loader() reference_dataset, comparison_dataset = data_splitter(data) report, _ = text_data_report( reference_dataset=reference_dataset, comparison_dataset=comparison_dataset, ) test_report, _ = text_data_test( reference_dataset=reference_dataset, comparison_dataset=comparison_dataset, ) text_analyzer(report) text_data_report_test_pipeline() ``` For a version of the same step that works with a single dataset, simply don't pass any comparison dataset: ```python text_data_report(reference_dataset=reference_dataset) ``` You should consult [the official Evidently documentation](https://docs.evidentlyai.com/reference/all-metrics) for more information on what each metric is useful for and what data columns it requires as input. The `evidently_report_step` step also allows for additional Report [options](https://docs.evidentlyai.com/user-guide/customization) to be passed to the `Report` constructor e.g.: ```python from zenml.integrations.evidently.steps import ( EvidentlyColumnMapping, ) text_data_report = evidently_report_step.with_options( parameters=dict( report_options = [ ( "evidently.options.ColorOptions", { "primary_color": "#5a86ad", "fill_color": "#fff4f2", "zero_line_color": "#016795", "current_data_color": "#c292a1", "reference_data_color": "#017b92", } ), ], ) ) ``` You can view [the complete list of configuration parameters](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-evidently/#zenml.integrations.evidently.steps.evidently\_report.evidently\_report\_step) in the SDK docs. #### Data Validation Aside from data profiling, Evidently can also be used to configure and run automated data validation tests on your data. Similar to using Evidently through ZenML to run data profiling, there are three ways you can use Evidently to run data validation tests in your ZenML pipelines that allow different levels of flexibility: * instantiate, configure and insert [the standard Evidently test step](evidently.md) shipped with ZenML into your pipelines. This is the easiest way and the recommended approach. * call the data validation methods provided by [the Evidently Data Validator](evidently.md#the-evidently-data-validator) in your custom step implementation. This method allows for more flexibility concerning what can happen in the pipeline step. * [use the Evidently library directly](evidently.md#call-evidently-directly) in your custom step implementation. This gives you complete freedom in how you are using Evidently's features. You can visualize Evidently reports in Jupyter notebooks or view them directly in the ZenML dashboard by clicking on the respective artifact in the pipeline run DAG. You can [visualize Evidently reports](evidently.md#visualizing-evidently-reports) in Jupyter notebooks or view them directly in the ZenML dashboard by clicking on the respective artifact in the pipeline run DAG. ZenML wraps the Evidently data validation functionality in the form of a standard Evidently test pipeline step that you can simply instantiate and insert in your pipeline. Here you can see how instantiating and configuring the standard Evidently test step can be done using our included `evidently_test_step` utility function: ```python from zenml.integrations.evidently.steps import ( EvidentlyColumnMapping, evidently_test_step, ) from zenml.integrations.evidently.tests import EvidentlyTestConfig text_data_test = evidently_test_step.with_options( parameters=dict( column_mapping=EvidentlyColumnMapping( target="Rating", numerical_features=["Age", "Positive_Feedback_Count"], categorical_features=[ "Division_Name", "Department_Name", "Class_Name", ], text_features=["Review_Text", "Title"], ), tests=[ EvidentlyTestConfig.test("DataQualityTestPreset"), EvidentlyTestConfig.test_generator( "TestColumnRegExp", columns=["Review_Text", "Title"], reg_exp=r"[A-Z][A-Za-z0-9 ]*", ), ], # We need to download the NLTK data for the TestColumnRegExp test download_nltk_data=True, ), ) ``` The configuration shown in the example is the equivalent of running the following Evidently code inside the step: ```python from evidently.tests import TestColumnRegExp from evidently.test_preset import DataQualityTestPreset from evidently import ColumnMapping from evidently.test_suite import TestSuite from evidently.tests.base_test import generate_column_tests import nltk nltk.download("words") nltk.download("wordnet") nltk.download("omw-1.4") column_mapping = ColumnMapping( target="Rating", numerical_features=["Age", "Positive_Feedback_Count"], categorical_features=[ "Division_Name", "Department_Name", "Class_Name", ], text_features=["Review_Text", "Title"], ) test_suite = TestSuite( tests=[ DataQualityTestPreset(), generate_column_tests( TestColumnRegExp, columns=["Review_Text", "Title"], parameters={"reg_exp": r"[A-Z][A-Za-z0-9 ]*"} ) ] ) # The datasets are those that are passed to the Evidently step # as input artifacts test_suite.run( current_data=current_dataset, reference_data=reference_dataset, column_mapping=column_mapping, ) ``` Let's break this down... We configure the `evidently_test_step` using parameters that you would normally pass to the Evidently `TestSuite` object to [configure and run an Evidently test suite](https://docs.evidentlyai.com/user-guide/tests-and-reports/custom-test-suite) . It consists of the following fields: * `column_mapping`: This is an `EvidentlyColumnMapping` object that is the exact equivalent of [the `ColumnMapping` object in Evidently](https://docs.evidentlyai.com/user-guide/input-data/column-mapping). It is used to describe the columns in the dataset and how they should be treated (e.g. as categorical, numerical, or text features). * `tests`: This is a list of `EvidentlyTestConfig` objects that are used to configure the tests that will be run as part of your test suite in a declarative way. This is the same as configuring the `tests` that go in the Evidently `TestSuite`. * `download_nltk_data`: This is a boolean that is used to indicate whether the NLTK data should be downloaded. This is only needed if you are using Evidently tests or test presets that handle text data, which require the NLTK data to be downloaded ahead of time. There are several ways you can reference the Evidently tests when configuring `EvidentlyTestConfig` items, similar to how you reference them in an `EvidentlyMetricConfig` object: * by class name: this is the easiest way to reference an Evidently test. You can use the name of a test or test preset class as it appears in the Evidently documentation (e.g.`"DataQualityTestPreset"`, `"TestColumnRegExp"`). * by full class path: you can also use the full Python class path of the test or test preset class ( e.g. `"evidently.test_preset.DataQualityTestPreset"`, `"evidently.tests.TestColumnRegExp"`). This is useful if you want to use tests or test presets that are not included in Evidently library. * by passing in the class itself: you can also import and pass in an Evidently test or test preset class itself, e.g.: ```python from evidently.tests import TestColumnRegExp ... evidently_test_step.with_options( parameters=dict( tests=[EvidentlyTestConfig.test(TestColumnRegExp)] ), ) ``` As can be seen in the example, there are two basic ways of adding tests to your Evidently test step configuration: * to add a single test or test preset: call `EvidentlyTestConfig.test` with an Evidently test or test preset class name (or class path or class). The rest of the parameters are the same ones that you would usually pass to the Evidently test or test preset class constructor. * to generate multiple tests, similar to calling [the Evidently column test generator](https://docs.evidentlyai.com/user-guide/tests-and-reports/test-metric-generator#column-test-generator): call `EvidentlyTestConfig.test_generator` with an Evidently test or test preset class name (or class path or class) and a list of column names. The rest of the parameters are the same ones that you would usually pass to the Evidently test or test preset class constructor. The ZenML Evidently test step can then be inserted into your pipeline where it can take in two datasets and outputs the Evidently test suite results generated in both JSON and HTML formats, e.g.: ```python @pipeline(enable_cache=False, settings={"docker": docker_settings}) def text_data_test_pipeline(): """Links all the steps together in a pipeline.""" data = data_loader() reference_dataset, comparison_dataset = data_splitter(data) json_report, html_report = text_data_test( reference_dataset=reference_dataset, comparison_dataset=comparison_dataset, ) text_data_test_pipeline() ``` For a version of the same step that works with a single dataset, simply don't pass any comparison dataset: ```python text_data_test(reference_dataset=reference_dataset) ``` You should consult [the official Evidently documentation](https://docs.evidentlyai.com/reference/all-tests) for more information on what each test is useful for and what data columns it requires as input. The `evidently_test_step` step also allows for additional Test [options](https://docs.evidentlyai.com/user-guide/customization) to be passed to the `TestSuite` constructor e.g.: ```python from zenml.integrations.evidently.steps import ( EvidentlyColumnMapping, ) text_data_test = evidently_test_step.with_options( parameters=dict( test_options = [ ( "evidently.options.ColorOptions", { "primary_color": "#5a86ad", "fill_color": "#fff4f2", "zero_line_color": "#016795", "current_data_color": "#c292a1", "reference_data_color": "#017b92", } ), ], ), ) ``` You can view [the complete list of configuration parameters](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-evidently/#zenml.integrations.evidently.steps.evidently\_test.evidently\_test\_step) in the SDK docs. #### The Evidently Data Validator The Evidently Data Validator implements the same interface as do all Data Validators, so this method forces you to maintain some level of compatibility with the overall Data Validator abstraction, which guarantees an easier migration in case you decide to switch to another Data Validator. All you have to do is call the Evidently Data Validator methods when you need to interact with Evidently to generate data reports or to run test suites, e.g.: ```python from typing_extensions import Annotated # or `from typing import Annotated on Python 3.9+ from typing import Tuple import pandas as pd from evidently.pipeline.column_mapping import ColumnMapping from zenml.integrations.evidently.data_validators import EvidentlyDataValidator from zenml.integrations.evidently.metrics import EvidentlyMetricConfig from zenml.integrations.evidently.tests import EvidentlyTestConfig from zenml.types import HTMLString from zenml import step @step def data_profiling( reference_dataset: pd.DataFrame, comparison_dataset: pd.DataFrame, ) -> Tuple[ Annotated[str, "report_json"], Annotated[HTMLString, "report_html"] ]: """Custom data profiling step with Evidently. Args: reference_dataset: a Pandas DataFrame comparison_dataset: a Pandas DataFrame of new data you wish to compare against the reference data Returns: The Evidently report rendered in JSON and HTML formats. """ # pre-processing (e.g. dataset preparation) can take place here data_validator = EvidentlyDataValidator.get_active_data_validator() report = data_validator.data_profiling( dataset=reference_dataset, comparison_dataset=comparison_dataset, profile_list=[ EvidentlyMetricConfig.metric("DataQualityPreset"), EvidentlyMetricConfig.metric( "TextOverviewPreset", column_name="Review_Text" ), EvidentlyMetricConfig.metric_generator( "ColumnRegExpMetric", columns=["Review_Text", "Title"], reg_exp=r"[A-Z][A-Za-z0-9 ]*", ), ], column_mapping = ColumnMapping( target="Rating", numerical_features=["Age", "Positive_Feedback_Count"], categorical_features=[ "Division_Name", "Department_Name", "Class_Name", ], text_features=["Review_Text", "Title"], ), download_nltk_data = True, ) # post-processing (e.g. interpret results, take actions) can happen here return report.json(), HTMLString(report.show(mode="inline").data) @step def data_validation( reference_dataset: pd.DataFrame, comparison_dataset: pd.DataFrame, ) -> Tuple[ Annotated[str, "test_json"], Annotated[HTMLString, "test_html"] ]: """Custom data validation step with Evidently. Args: reference_dataset: a Pandas DataFrame comparison_dataset: a Pandas DataFrame of new data you wish to compare against the reference data Returns: The Evidently test suite results rendered in JSON and HTML formats. """ # pre-processing (e.g. dataset preparation) can take place here data_validator = EvidentlyDataValidator.get_active_data_validator() test_suite = data_validator.data_validation( dataset=reference_dataset, comparison_dataset=comparison_dataset, check_list=[ EvidentlyTestConfig.test("DataQualityTestPreset"), EvidentlyTestConfig.test_generator( "TestColumnRegExp", columns=["Review_Text", "Title"], reg_exp=r"[A-Z][A-Za-z0-9 ]*", ), ], column_mapping = ColumnMapping( target="Rating", numerical_features=["Age", "Positive_Feedback_Count"], categorical_features=[ "Division_Name", "Department_Name", "Class_Name", ], text_features=["Review_Text", "Title"], ), download_nltk_data = True, ) # post-processing (e.g. interpret results, take actions) can happen here return test_suite.json(), HTMLString(test_suite.show(mode="inline").data) ``` Have a look at [the complete list of methods and parameters available in the `EvidentlyDataValidator` API](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-evidently/#zenml.integrations.evidently.data\_validators.evidently\_data\_validator.EvidentlyDataValidator) in the SDK docs. #### Call Evidently directly You can use the Evidently library directly in your custom pipeline steps, e.g.: ```python from typing_extensions import Annotated # or `from typing import Annotated` on Python 3.9+ from typing import Tuple import pandas as pd from evidently.report import Report import evidently.metric_preset as metric_preset from evidently.test_suite import TestSuite import evidently.test_preset as test_preset from evidently.pipeline.column_mapping import ColumnMapping from zenml.types import HTMLString from zenml import step @step def data_profiler( dataset: pd.DataFrame, ) -> Tuple[ Annotated[str, "report_json"], Annotated[HTMLString, "report_html"] ]: """Custom data profiler step with Evidently Args: dataset: a Pandas DataFrame Returns: Evidently report generated for the dataset in JSON and HTML format. """ # pre-processing (e.g. dataset preparation) can take place here report = Report(metrics=[metric_preset.DataQualityPreset()]) report.run( current_data=dataset, reference_data=dataset, ) # post-processing (e.g. interpret results, take actions) can happen here return report.json(), HTMLString(report.show(mode="inline").data) @step def data_tester( dataset: pd.DataFrame, ) -> Tuple[ Annotated[str, "test_json"], Annotated[HTMLString, "test_html"] ]: """Custom data tester step with Evidently Args: dataset: a Pandas DataFrame Returns: Evidently test results generated for the dataset in JSON and HTML format. """ # pre-processing (e.g. dataset preparation) can take place here test_suite = TestSuite(metrics=[test_preset.DataQualityTestPreset()]) report.run( current_data=dataset, reference_data=dataset, ) # post-processing (e.g. interpret results, take actions) can happen here return test_suite.json(), HTMLString(test_suite.show(mode="inline").data) ``` ### Visualizing Evidently Reports You can view visualizations of the Evidently reports generated by your pipeline steps directly in the ZenML dashboard by clicking on the respective artifact in the pipeline run DAG. Alternatively, if you are running inside a Jupyter notebook, you can load and render the reports using the [artifact.visualize() method](../../how-to/data-artifact-management/visualize-artifacts/README.md), e.g.: ```python from zenml.client import Client def visualize_results(pipeline_name: str, step_name: str) -> None: pipeline = Client().get_pipeline(pipeline=pipeline_name) evidently_step = pipeline.last_run.steps[step_name] evidently_step.visualize() if __name__ == "__main__": visualize_results("text_data_report_pipeline", "text_report") visualize_results("text_data_test_pipeline", "text_test") ``` ![Evidently metrics report visualization](../../.gitbook/assets/evidently-metrics-report.png) ![Evidently test results visualization](../../.gitbook/assets/evidently-test-results.png)
ZenML Scarf
================ File: docs/book/component-guide/data-validators/great-expectations.md ================ --- description: >- How to use Great Expectations to run data quality checks in your pipelines and document the results --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Great Expectations The Great Expectations [Data Validator](./data-validators.md) flavor provided with the ZenML integration uses [Great Expectations](https://greatexpectations.io/) to run data profiling and data quality tests on the data circulated through your pipelines. The test results can be used to implement automated corrective actions in your pipelines. They are also automatically rendered into documentation for further visual interpretation and evaluation. ### When would you want to use it? [Great Expectations](https://greatexpectations.io/) is an open-source library that helps keep the quality of your data in check through data testing, documentation, and profiling, and to improve communication and observability. Great Expectations works with tabular data in a variety of formats and data sources, of which ZenML currently supports only `pandas.DataFrame` as part of its pipelines. You should use the Great Expectations Data Validator when you need the following data validation features that are possible with Great Expectations: * [Data Profiling](https://docs.greatexpectations.io/docs/oss/guides/expectations/creating_custom_expectations/how_to_add_support_for_the_auto_initializing_framework_to_a_custom_expectation/#build-a-custom-profiler-for-your-expectation): generates a set of validation rules (Expectations) automatically by inferring them from the properties of an input dataset. * [Data Quality](https://docs.greatexpectations.io/docs/oss/guides/validation/checkpoints/how_to_pass_an_in_memory_dataframe_to_a_checkpoint/): runs a set of predefined or inferred validation rules (Expectations) against an in-memory dataset. * [Data Docs](https://docs.greatexpectations.io/docs/reference/learn/terms/data_docs_store/): generate and maintain human-readable documentation of all your data validation rules, data quality checks and their results. You should consider one of the other [Data Validator flavors](./data-validators.md#data-validator-flavors) if you need a different set of data validation features. ### How do you deploy it? The Great Expectations Data Validator flavor is included in the Great Expectations ZenML integration, you need to install it on your local machine to be able to register a Great Expectations Data Validator and add it to your stack: ```shell zenml integration install great_expectations -y ``` Depending on how you configure the Great Expectations Data Validator, it can reduce or even completely eliminate the complexity associated with setting up the store backends for Great Expectations. If you're only looking for a quick and easy way of adding Great Expectations to your stack and are not concerned with the configuration details, you can simply run: ```shell # Register the Great Expectations data validator zenml data-validator register ge_data_validator --flavor=great_expectations # Register and set a stack with the new data validator zenml stack register custom_stack -dv ge_data_validator ... --set ``` If you already have a Great Expectations deployment, you can configure the Great Expectations Data Validator to reuse or even replace your current configuration. You should consider the pros and cons of every deployment use-case and choose the one that best fits your needs: 1. let ZenML initialize and manage the Great Expectations configuration. The Artifact Store will serve as a storage backend for all the information that Great Expectations needs to persist (e.g. Expectation Suites, Validation Results). However, you will not be able to setup new Data Sources, Metadata Stores or Data Docs sites. Any changes you try and make to the configuration through code will not be persisted and will be lost when your pipeline completes or your local process exits. 2. use ZenML with your existing Great Expectations configuration. You can tell ZenML to replace your existing Metadata Stores with the active ZenML Artifact Store by setting the `configure_zenml_stores` attribute in the Data Validator. The downside is that you will only be able to run pipelines locally with this setup, given that the Great Expectations configuration is a file on your local machine. 3. migrate your existing Great Expectations configuration to ZenML. This is a compromise between 1. and 2. that allows you to continue to use your existing Data Sources, Metadata Stores and Data Docs sites even when running pipelines remotely. {% hint style="warning" %} Some Great Expectations CLI commands will not work well with the deployment methods that puts ZenML in charge of your Great Expectations configuration (i.e. 1. and 3.). You will be required to use Python code to manage your Expectations and you will have to edit the Jupyter notebooks generated by the Great Expectations CLI to connect them to your ZenML managed configuration. . {% endhint %} {% tabs %} {% tab title="Let ZenML Manage The Configuration" %} The default Data Validator setup plugs Great Expectations directly into the [Artifact Store](../artifact-stores/artifact-stores.md) component that is part of the same stack. As a result, the Expectation Suites, Validation Results and Data Docs are stored in the ZenML Artifact Store and you don't have to configure Great Expectations at all, ZenML takes care of that for you: ```shell # Register the Great Expectations data validator zenml data-validator register ge_data_validator --flavor=great_expectations # Register and set a stack with the new data validator zenml stack register custom_stack -dv ge_data_validator ... --set ``` {% endtab %} {% tab title="Use Your Own Configuration" %} If you have an existing Great Expectations configuration that you would like to reuse with your ZenML pipelines, the Data Validator allows you to do so. All you need is to point it to the folder where your local `great_expectations.yaml` configuration file is located: ```shell # Register the Great Expectations data validator zenml data-validator register ge_data_validator --flavor=great_expectations \ --context_root_dir=/path/to/my/great_expectations # Register and set a stack with the new data validator zenml stack register custom_stack -dv ge_data_validator ... --set ``` You can continue to edit your local Great Expectations configuration (e.g. add new Data Sources, update the Metadata Stores etc.) and these changes will be visible in your ZenML pipelines. You can also use the Great Expectations CLI as usual to manage your configuration and your Expectations. {% endtab %} {% tab title="Migrate Your Configuration to ZenML" %} This deployment method migrates your existing Great Expectations configuration to ZenML and allows you to use it with local as well as remote orchestrators. You have to load the Great Expectations configuration contents in one of the Data Validator configuration parameters using the `@` operator, e.g.: ```shell # Register the Great Expectations data validator zenml data-validator register ge_data_validator --flavor=great_expectations \ --context_config=@/path/to/my/great_expectations/great_expectations.yaml # Register and set a stack with the new data validator zenml stack register custom_stack -dv ge_data_validator ... --set ``` When you are migrating your existing Great Expectations configuration to ZenML, keep in mind that the Metadata Stores that you configured there will also need to be accessible from the location where pipelines are running. For example, you cannot use a non-local orchestrator with a Great Expectations Metadata Store that is located on your filesystem. {% endtab %} {% endtabs %} #### Advanced Configuration The Great Expectations Data Validator has a few advanced configuration attributes that might be useful for your particular use-case: * `configure_zenml_stores`: if set, ZenML will automatically update the Great Expectation configuration to include Metadata Stores that use the Artifact Store as a backend. If neither `context_root_dir` nor `context_config` are set, this is the default behavior. You can set this flag to use the ZenML Artifact Store as a backend for Great Expectations with any of the deployment methods described above. Note that ZenML will not copy the information in your existing Great Expectations stores (e.g. Expectation Suites, Validation Results) in the ZenML Artifact Store. This is something that you will have to do yourself. * `configure_local_docs`: set this flag to configure a local Data Docs site where Great Expectations docs are generated and can be visualized locally. Use this in case you don't already have a local Data Docs site in your existing Great Expectations configuration. For more, up-to-date information on the Great Expectations Data Validator configuration, you can have a look at [the SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-great\_expectations/#zenml.integrations.great\_expectations.data\_validators.ge\_data\_validator.GreatExpectationsDataValidator) . ### How do you use it? The core Great Expectations concepts that you should be aware of when using it within ZenML pipelines are Expectations / Expectation Suites, Validations and Data Docs. ZenML wraps the Great Expectations' functionality in the form of two standard steps: * a Great Expectations data profiler that can be used to automatically generate Expectation Suites from an input `pandas.DataFrame` dataset * a Great Expectations data validator that uses an existing Expectation Suite to validate an input `pandas.DataFrame` dataset You can visualize Great Expectations Suites and Results in Jupyter notebooks or view them directly in the ZenML dashboard. #### The Great Expectation's data profiler step The standard Great Expectation's data profiler step builds an Expectation Suite automatically by running a [`UserConfigurableProfiler`](https://docs.greatexpectations.io/docs/guides/expectations/how\_to\_create\_and\_edit\_expectations\_with\_a\_profiler) on an input `pandas.DataFrame` dataset. The generated Expectation Suite is saved in the Great Expectations Expectation Store, but also returned as an `ExpectationSuite` artifact that is versioned and saved in the ZenML Artifact Store. The step automatically rebuilds the Data Docs. At a minimum, the step configuration expects a name to be used for the Expectation Suite: ```python from zenml.integrations.great_expectations.steps import ( great_expectations_profiler_step, ) ge_profiler_step = great_expectations_profiler_step.with_options( parameters={ "expectation_suite_name": "steel_plates_suite", "data_asset_name": "steel_plates_train_df", } ) ``` The step can then be inserted into your pipeline where it can take in a pandas dataframe, e.g.: ```python from zenml import pipeline docker_settings = DockerSettings(required_integrations=[SKLEARN, GREAT_EXPECTATIONS]) @pipeline(settings={"docker": docker_settings}) def profiling_pipeline(): """Data profiling pipeline for Great Expectations. The pipeline imports a reference dataset from a source then uses the builtin Great Expectations profiler step to generate an expectation suite (i.e. validation rules) inferred from the schema and statistical properties of the reference dataset. Args: importer: reference data importer step profiler: data profiler step """ dataset, _ = importer() ge_profiler_step(dataset) profiling_pipeline() ``` As can be seen from the [step definition](https://apidocs.zenml.io/latest/integration\_code\_docs/integrations-great\_expectations/#zenml.integrations.great\_expectations.steps.ge\_profiler.great\_expectations\_profiler\_step) , the step takes in a `pandas.DataFrame` dataset, and it returns a Great Expectations `ExpectationSuite` object: ```python @step def great_expectations_profiler_step( dataset: pd.DataFrame, expectation_suite_name: str, data_asset_name: Optional[str] = None, profiler_kwargs: Optional[Dict[str, Any]] = None, overwrite_existing_suite: bool = True, ) -> ExpectationSuite: ... ``` You can view [the complete list of configuration parameters](https://apidocs.zenml.io/latest/integration\_code\_docs/integrations-great\_expectations/#zenml.integrations.great\_expectations.steps.ge\_profiler.great\_expectations\_profiler\_step) in the SDK docs. #### The Great Expectations data validator step The standard Great Expectations data validator step validates an input `pandas.DataFrame` dataset by running an existing Expectation Suite on it. The validation results are saved in the Great Expectations Validation Store, but also returned as an `CheckpointResult` artifact that is versioned and saved in the ZenML Artifact Store. The step automatically rebuilds the Data Docs. At a minimum, the step configuration expects the name of the Expectation Suite to be used for the validation: ```python from zenml.integrations.great_expectations.steps import ( great_expectations_validator_step, ) ge_validator_step = great_expectations_validator_step.with_options( parameters={ "expectation_suite_name": "steel_plates_suite", "data_asset_name": "steel_plates_train_df", } ) ``` The step can then be inserted into your pipeline where it can take in a pandas dataframe and a bool flag used solely for order reinforcement purposes, e.g.: ```python docker_settings = DockerSettings(required_integrations=[SKLEARN, GREAT_EXPECTATIONS]) @pipeline(settings={"docker": docker_settings}) def validation_pipeline(): """Data validation pipeline for Great Expectations. The pipeline imports a test data from a source, then uses the builtin Great Expectations data validation step to validate the dataset against the expectation suite generated in the profiling pipeline. Args: importer: test data importer step validator: dataset validation step checker: checks the validation results """ dataset, condition = importer() results = ge_validator_step(dataset, condition) message = checker(results) validation_pipeline() ``` As can be seen from the [step definition](https://apidocs.zenml.io/latest/integration\_code\_docs/integrations-great\_expectations/#zenml.integrations.great\_expectations.steps.ge\_validator.great\_expectations\_validator\_step) , the step takes in a `pandas.DataFrame` dataset and a boolean `condition` and it returns a Great Expectations `CheckpointResult` object. The boolean `condition` is only used as a means of ordering steps in a pipeline (e.g. if you must force it to run only after the data profiling step generates an Expectation Suite): ```python @step def great_expectations_validator_step( dataset: pd.DataFrame, expectation_suite_name: str, data_asset_name: Optional[str] = None, action_list: Optional[List[Dict[str, Any]]] = None, exit_on_error: bool = False, ) -> CheckpointResult: ``` You can view [the complete list of configuration parameters](https://apidocs.zenml.io/latest/integration\_code\_docs/integrations-great\_expectations/#zenml.integrations.great\_expectations.steps.ge\_validator.great\_expectations\_validator\_step) in the SDK docs. #### Call Great Expectations directly You can use the Great Expectations library directly in your custom pipeline steps, while leveraging ZenML's capability of serializing, versioning and storing the `ExpectationSuite` and `CheckpointResult` objects in its Artifact Store. To use the Great Expectations configuration managed by ZenML while interacting with the Great Expectations library directly, you need to use the Data Context managed by ZenML instead of the default one provided by Great Expectations, e.g.: ```python import great_expectations as ge from zenml.integrations.great_expectations.data_validators import ( GreatExpectationsDataValidator ) import pandas as pd from great_expectations.core import ExpectationSuite from zenml import step @step def create_custom_expectation_suite( ) -> ExpectationSuite: """Custom step that creates an Expectation Suite Returns: An Expectation Suite """ context = GreatExpectationsDataValidator.get_data_context() # instead of: # context = ge.get_context() expectation_suite_name = "custom_suite" suite = context.create_expectation_suite( expectation_suite_name=expectation_suite_name ) expectation_configuration = ExpectationConfiguration(...) suite.add_expectation(expectation_configuration=expectation_configuration) ... context.save_expectation_suite( expectation_suite=suite, expectation_suite_name=expectation_suite_name, ) context.build_data_docs() return suite ``` The same approach must be used if you are using a Great Expectations configuration managed by ZenML and are using the Jupyter notebooks generated by the Great Expectations CLI. #### Visualizing Great Expectations Suites and Results You can view visualizations of the suites and results generated by your pipeline steps directly in the ZenML dashboard by clicking on the respective artifact in the pipeline run DAG. Alternatively, if you are running inside a Jupyter notebook, you can load and render the suites and results using the [`artifact.visualize()` method](../../how-to/data-artifact-management/visualize-artifacts/README.md), e.g.: ```python from zenml.client import Client def visualize_results(pipeline_name: str, step_name: str) -> None: pipeline = Client().get_pipeline(pipeline_name) last_run = pipeline.last_run validation_step = last_run.steps[step_name] validation_step.visualize() if __name__ == "__main__": visualize_results("validation_pipeline", "profiler") visualize_results("validation_pipeline", "train_validator") visualize_results("validation_pipeline", "test_validator") ``` ![Expectations Suite Visualization](<../../.gitbook/assets/expectation-suite.png>) ![Validation Results Visualization](<../../.gitbook/assets/validation-result.png>)
ZenML Scarf
================ File: docs/book/component-guide/data-validators/whylogs.md ================ --- description: >- How to collect and visualize statistics to track changes in your pipelines' data with whylogs/WhyLabs profiling. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Whylogs The whylogs/WhyLabs [Data Validator](./data-validators.md) flavor provided with the ZenML integration uses [whylogs](https://whylabs.ai/whylogs) and [WhyLabs](https://whylabs.ai) to generate and track data profiles, highly accurate descriptive representations of your data. The profiles can be used to implement automated corrective actions in your pipelines, or to render interactive representations for further visual interpretation, evaluation and documentation. ### When would you want to use it? [Whylogs](https://whylabs.ai/whylogs) is an open-source library that analyzes your data and creates statistical summaries called whylogs profiles. Whylogs profiles can be processed in your pipelines and visualized locally or uploaded to the [WhyLabs platform](https://whylabs.ai/), where more in depth analysis can be carried out. Even though [whylogs also supports other data types](https://github.com/whylabs/whylogs#data-types), the ZenML whylogs integration currently only works with tabular data in `pandas.DataFrame` format. You should use the whylogs/WhyLabs Data Validator when you need the following data validation features that are possible with whylogs and WhyLabs: * Data Quality: validate data quality in model inputs or in a data pipeline * Data Drift: detect data drift in model input features * Model Drift: Detect training-serving skew, concept drift, and model performance degradation You should consider one of the other [Data Validator flavors](./data-validators.md#data-validator-flavors) if you need a different set of data validation features. ### How do you deploy it? The whylogs Data Validator flavor is included in the whylogs ZenML integration, you need to install it on your local machine to be able to register a whylogs Data Validator and add it to your stack: ```shell zenml integration install whylogs -y ``` If you don't need to connect to the WhyLabs platform to upload and store the generated whylogs data profiles, the Data Validator stack component does not require any configuration parameters. Adding it to a stack is as simple as running e.g.: ```shell # Register the whylogs data validator zenml data-validator register whylogs_data_validator --flavor=whylogs # Register and set a stack with the new data validator zenml stack register custom_stack -dv whylogs_data_validator ... --set ``` Adding WhyLabs logging capabilities to your whylogs Data Validator is just slightly more complicated, as you also need to create a [ZenML Secret](../../getting-started/deploying-zenml/secret-management.md) to store the sensitive WhyLabs authentication information in a secure location and then reference the secret in the Data Validator configuration. To generate a WhyLabs access token, you can follow [the official WhyLabs instructions documented here](https://docs.whylabs.ai/docs/whylabs-api/#creating-an-api-token) . Then, you can register the whylogs Data Validator with WhyLabs logging capabilities as follows: ```shell # Create the secret referenced in the data validator zenml secret create whylabs_secret \ --whylabs_default_org_id= \ --whylabs_api_key= # Register the whylogs data validator zenml data-validator register whylogs_data_validator --flavor=whylogs \ --authentication_secret=whylabs_secret ``` You'll also need to enable whylabs logging for your custom pipeline steps if you want to upload the whylogs data profiles that they return as artifacts to the WhyLabs platform. This is enabled by default for the standard whylogs step. For custom steps, you can enable WhyLabs logging by setting the `upload_to_whylabs` parameter to `True` in the step configuration, e.g.: ```python from typing_extensions import Annotated # or `from typing import Annotated on Python 3.9+ from typing import Tuple import pandas as pd import whylogs as why from sklearn import datasets from whylogs.core import DatasetProfileView from zenml.integrations.whylogs.flavors.whylogs_data_validator_flavor import ( WhylogsDataValidatorSettings, ) from zenml import step @step( settings={ "data_validator": WhylogsDataValidatorSettings( enable_whylabs=True, dataset_id="model-1" ) } ) def data_loader() -> Tuple[ Annotated[pd.DataFrame, "data"], Annotated[DatasetProfileView, "profile"] ]: """Load the diabetes dataset.""" X, y = datasets.load_diabetes(return_X_y=True, as_frame=True) # merge X and y together df = pd.merge(X, y, left_index=True, right_index=True) profile = why.log(pandas=df).profile().view() return df, profile ``` ### How do you use it? Whylogs's profiling functions take in a `pandas.DataFrame` dataset generate a `DatasetProfileView` object containing all the relevant information extracted from the dataset. There are three ways you can use whylogs in your ZenML pipelines that allow different levels of flexibility: * instantiate, configure and insert [the standard `WhylogsProfilerStep`](whylogs.md#the-whylogs-standard-step) shipped with ZenML into your pipelines. This is the easiest way and the recommended approach, but can only be customized through the supported step configuration parameters. * call the data validation methods provided by [the whylogs Data Validator](whylogs.md#the-whylogs-data-validator) in your custom step implementation. This method allows for more flexibility concerning what can happen in the pipeline step, but you are still limited to the functionality implemented in the Data Validator. * [use the whylogs library directly](whylogs.md#call-whylogs-directly) in your custom step implementation. This gives you complete freedom in how you are using whylogs's features. You can [visualize whylogs profiles](whylogs.md#visualizing-whylogs-profiles) in Jupyter notebooks or view them directly in the ZenML dashboard. #### The whylogs standard step ZenML wraps the whylogs/WhyLabs functionality in the form of a standard `WhylogsProfilerStep` step. The only field in the step config is a `dataset_timestamp` attribute which is only relevant when you upload the profiles to WhyLabs that uses this field to group and merge together profiles belonging to the same dataset. The helper function `get_whylogs_profiler_step` used to create an instance of this standard step takes in an optional `dataset_id` parameter that is also used only in the context of WhyLabs upload to identify the model in the context of which the profile is uploaded, e.g.: ```python from zenml.integrations.whylogs.steps import get_whylogs_profiler_step train_data_profiler = get_whylogs_profiler_step(dataset_id="model-2") test_data_profiler = get_whylogs_profiler_step(dataset_id="model-3") ``` The step can then be inserted into your pipeline where it can take in a `pandas.DataFrame` dataset, e.g.: ```python from zenml import pipeline @pipeline def data_profiling_pipeline(): data, _ = data_loader() train, test = data_splitter(data) train_data_profiler(train) test_data_profiler(test) data_profiling_pipeline() ``` As can be seen from the [step definition](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-whylogs/#zenml.integrations.whylogs.steps.whylogs\_profiler.whylogs\_profiler\_step) , the step takes in a dataset and returns a whylogs `DatasetProfileView` object: ```python @step def whylogs_profiler_step( dataset: pd.DataFrame, dataset_timestamp: Optional[datetime.datetime] = None, ) -> DatasetProfileView: ... ``` You should consult [the official whylogs documentation](https://whylogs.readthedocs.io/en/latest/index.html) for more information on what you can do with the collected profiles. You can view [the complete list of configuration parameters](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-whylogs/#zenml.integrations.whylogs.steps.whylogs\_profiler.WhylogsProfilerConfig) in the SDK docs. #### The whylogs Data Validator The whylogs Data Validator implements the same interface as do all Data Validators, so this method forces you to maintain some level of compatibility with the overall Data Validator abstraction, which guarantees an easier migration in case you decide to switch to another Data Validator. All you have to do is call the whylogs Data Validator methods when you need to interact with whylogs to generate data profiles. You may optionally enable whylabs logging to automatically upload the returned whylogs profile to WhyLabs, e.g.: ```python import pandas as pd from whylogs.core import DatasetProfileView from zenml.integrations.whylogs.data_validators.whylogs_data_validator import ( WhylogsDataValidator, ) from zenml.integrations.whylogs.flavors.whylogs_data_validator_flavor import ( WhylogsDataValidatorSettings, ) from zenml import step whylogs_settings = WhylogsDataValidatorSettings( enable_whylabs=True, dataset_id="" ) @step( settings={ "data_validator": whylogs_settings } ) def data_profiler( dataset: pd.DataFrame, ) -> DatasetProfileView: """Custom data profiler step with whylogs Args: dataset: a Pandas DataFrame Returns: Whylogs profile generated for the data """ # validation pre-processing (e.g. dataset preparation) can take place here data_validator = WhylogsDataValidator.get_active_data_validator() profile = data_validator.data_profiling( dataset, ) # optionally upload the profile to WhyLabs, if WhyLabs credentials are configured data_validator.upload_profile_view(profile) # validation post-processing (e.g. interpret results, take actions) can happen here return profile ``` Have a look at [the complete list of methods and parameters available in the `WhylogsDataValidator` API](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-whylogs/#zenml.integrations.whylogs.data\_validators.whylogs\_data\_validator.WhylogsDataValidator) in the SDK docs. #### Call whylogs directly You can use the whylogs library directly in your custom pipeline steps, and only leverage ZenML's capability of serializing, versioning and storing the `DatasetProfileView` objects in its Artifact Store. You may optionally enable whylabs logging to automatically upload the returned whylogs profile to WhyLabs, e.g.: ```python import pandas as pd from whylogs.core import DatasetProfileView import whylogs as why from zenml import step from zenml.integrations.whylogs.flavors.whylogs_data_validator_flavor import ( WhylogsDataValidatorSettings, ) whylogs_settings = WhylogsDataValidatorSettings( enable_whylabs=True, dataset_id="" ) @step( settings={ "data_validator": whylogs_settings } ) def data_profiler( dataset: pd.DataFrame, ) -> DatasetProfileView: """Custom data profiler step with whylogs Args: dataset: a Pandas DataFrame Returns: Whylogs Profile generated for the dataset """ # validation pre-processing (e.g. dataset preparation) can take place here results = why.log(dataset) profile = results.profile() # validation post-processing (e.g. interpret results, take actions) can happen here return profile.view() ``` ### Visualizing whylogs Profiles You can view visualizations of the whylogs profiles generated by your pipeline steps directly in the ZenML dashboard by clicking on the respective artifact in the pipeline run DAG. Alternatively, if you are running inside a Jupyter notebook, you can load and render the whylogs profiles using the [artifact.visualize() method](../../how-to/data-artifact-management/visualize-artifacts/README.md), e.g.: ```python from zenml.client import Client def visualize_statistics( step_name: str, reference_step_name: Optional[str] = None ) -> None: """Helper function to visualize whylogs statistics from step artifacts. Args: step_name: step that generated and returned a whylogs profile reference_step_name: an optional second step that generated a whylogs profile to use for data drift visualization where two whylogs profiles are required. """ pipe = Client().get_pipeline(pipeline="data_profiling_pipeline") whylogs_step = pipe.last_run.steps[step_name] whylogs_step.visualize() if __name__ == "__main__": visualize_statistics("data_loader") visualize_statistics("train_data_profiler", "test_data_profiler") ``` ![Whylogs Visualization Example 1](<../../.gitbook/assets/whylogs-visualizer-01.png>) ![Whylogs Visualization Example 2](../../.gitbook/assets/whylogs-visualizer-02.png)
ZenML Scarf
================ File: docs/book/component-guide/experiment-trackers/comet.md ================ --- description: Logging and visualizing experiments with Comet. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Comet The Comet Experiment Tracker is an [Experiment Tracker](./experiment-trackers.md) flavor provided with the Comet ZenML integration that uses [the Comet experiment tracking platform](https://www.comet.com/site/products/ml-experiment-tracking/) to log and visualize information from your pipeline steps (e.g., models, parameters, metrics).

A pipeline with a Comet experiment tracker url as metadata

### When would you want to use it? [Comet](https://www.comet.com/site/products/ml-experiment-tracking/) is a popular platform that you would normally use in the iterative ML experimentation phase to track and visualize experiment results. That doesn't mean that it cannot be repurposed to track and visualize the results produced by your automated pipeline runs, as you make the transition towards a more production-oriented workflow. You should use the Comet Experiment Tracker: * if you have already been using Comet to track experiment results for your project and would like to continue doing so as you are incorporating MLOps workflows and best practices in your project through ZenML. * if you are looking for a more visually interactive way of navigating the results produced from your ZenML pipeline runs (e.g., models, metrics, datasets) * if you would like to connect ZenML to Comet to share the artifacts and metrics logged by your pipelines with your team, organization, or external stakeholders You should consider one of the other [Experiment Tracker flavors](./experiment-trackers.md#experiment-tracker-flavors) if you have never worked with Comet before and would rather use another experiment tracking tool that you are more familiar with. ### How do you deploy it? The Comet Experiment Tracker flavor is provided by the Comet ZenML integration. You need to install it on your local machine to be able to register a Comet Experiment Tracker and add it to your stack: ```bash zenml integration install comet -y ``` The Comet Experiment Tracker needs to be configured with the credentials required to connect to the Comet platform using one of the available authentication methods. #### Authentication Methods You need to configure the following credentials for authentication to the Comet platform: * `api_key`: Mandatory API key token of your Comet account. * `project_name`: The name of the project where you're sending the new experiment. If the project is not specified, the experiment is put in the default project associated with your API key. * `workspace`: Optional. The name of the workspace where your project is located. If not specified, the default workspace associated with your API key will be used. {% tabs %} {% tab title="ZenML Secret (Recommended)" %} This method requires you to [configure a ZenML secret](../../getting-started/deploying-zenml/secret-management.md) to store the Comet tracking service credentials securely. You can create the secret using the `zenml secret create` command: ```bash zenml secret create comet_secret \ --workspace= \ --project_name= \ --api_key= ``` Once the secret is created, you can use it to configure the Comet Experiment Tracker: ```bash # Reference the workspace, project, and api-key in our experiment tracker component zenml experiment-tracker register comet_tracker \ --flavor=comet \ --workspace={{comet_secret.workspace}} \ --project_name={{comet_secret.project_name}} \ --api_key={{comet_secret.api_key}} ... # Register and set a stack with the new experiment tracker zenml stack register custom_stack -e comet_experiment_tracker ... --set ``` {% hint style="info" %} Read more about [ZenML Secrets](../../getting-started/deploying-zenml/secret-management.md) in the ZenML documentation. {% endhint %} {% endtab %} {% tab title="Basic Authentication" %} This option configures the credentials for the Comet platform directly as stack component attributes. {% hint style="warning" %} This is not recommended for production settings as the credentials won't be stored securely and will be clearly visible in the stack configuration. {% endhint %} ```bash # Register the Comet experiment tracker zenml experiment-tracker register comet_experiment_tracker --flavor=comet \ --workspace= --project_name= --api_key= # Register and set a stack with the new experiment tracker zenml stack register custom_stack -e comet_experiment_tracker ... --set ``` {% endtab %} {% endtabs %}

A stack with the Comet experiment tracker

For more up-to-date information on the Comet Experiment Tracker implementation and its configuration, you can have a look at [the SDK docs for our Comet integration](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-comet/#zenml.integrations.comet.flavors.comet_experiment_tracker_flavor.CometExperimentTrackerConfig). ### How do you use it? To be able to log information from a ZenML pipeline step using the Comet Experiment Tracker component in the active stack, you need to enable an experiment tracker using the `@step` decorator. Then use Comet logging capabilities as you would normally do, e.g.: ```python from zenml.client import Client experiment_tracker = Client().active_stack.experiment_tracker @step(experiment_tracker=experiment_tracker.name) def my_step(): ... # go through some experiment tracker methods experiment_tracker.log_metrics({"my_metric": 42}) experiment_tracker.log_params({"my_param": "hello"}) # or use the Experiment object directly experiment_tracker.experiment.log_model(...) # or pass the Comet Experiment object into helper methods from comet_ml.integration.sklearn import log_model log_model( experiment=experiment_tracker.experiment, model_name="SVC", model=model, ) ... ``` {% hint style="info" %} Instead of hardcoding an experiment tracker name, you can also use the [Client](../../reference/python-client.md) to dynamically use the experiment tracker of your active stack, as shown in the example above. {% endhint %} ### Comet UI Comet comes with a web-based UI that you can use to find further details about your tracked experiments. Every ZenML step that uses Comet should create a separate experiment which you can inspect in the Comet UI.

A confusion matrix logged in the Comet UI

A model tracked in the Comet UI

You can find the URL of the Comet experiment linked to a specific ZenML run via the metadata of the step in which the experiment tracker was used: ```python from zenml.client import Client last_run = client.get_pipeline("").last_run trainer_step = last_run.get_step("") tracking_url = trainer_step.run_metadata["experiment_tracker_url"].value print(tracking_url) ```

A pipeline with a Comet experiment tracker url as metadata

Alternatively, you can see an overview of all experiments at `https://www.comet.com/{WORKSPACE_NAME}/{PROJECT_NAME}/experiments/`. {% hint style="info" %} The naming convention of each Comet experiment is `{pipeline_run_name}_{step_name}` (e.g., `comet_example_pipeline-25_Apr_22-20_06_33_535737_my_step`), and each experiment will be tagged with both `pipeline_name` and `pipeline_run_name`, which you can use to group and filter experiments. {% endhint %} ## Full Code Example This section combines all the code from this section into one simple script that you can use to run easily:
Code Example of this Section ```python from comet_ml.integration.sklearn import log_model import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC from sklearn.metrics import accuracy_score from typing import Tuple from zenml import pipeline, step from zenml.client import Client from zenml.integrations.comet.flavors.comet_experiment_tracker_flavor import ( CometExperimentTrackerSettings, ) from zenml.integrations.comet.experiment_trackers import CometExperimentTracker # Get the experiment tracker from the active stack experiment_tracker: CometExperimentTracker = Client().active_stack.experiment_tracker @step def load_data() -> Tuple[np.ndarray, np.ndarray]: iris = load_iris() X = iris.data y = iris.target return X, y @step def preprocess_data( X: np.ndarray, y: np.ndarray ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) return X_train_scaled, X_test_scaled, y_train, y_test @step(experiment_tracker=experiment_tracker.name) def train_model(X_train: np.ndarray, y_train: np.ndarray) -> SVC: model = SVC(kernel="rbf", C=1.0) model.fit(X_train, y_train) log_model( experiment=experiment_tracker.experiment, model_name="SVC", model=model, ) return model @step(experiment_tracker=experiment_tracker.name) def evaluate_model(model: SVC, X_test: np.ndarray, y_test: np.ndarray) -> float: y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) # Log metrics using Comet experiment_tracker.log_metrics({"accuracy": accuracy}) experiment_tracker.experiment.log_confusion_matrix(y_test, y_pred) return accuracy @pipeline(enable_cache=False) def iris_classification_pipeline(): X, y = load_data() X_train, X_test, y_train, y_test = preprocess_data(X, y) model = train_model(X_train, y_train) accuracy = evaluate_model(model, X_test, y_test) if __name__ == "__main__": # Configure Comet settings comet_settings = CometExperimentTrackerSettings(tags=["iris_classification", "svm"]) # Run the pipeline last_run = iris_classification_pipeline.with_options( settings={"experiment_tracker": comet_settings} )() # Get the URLs for the trainer and evaluator steps trainer_step, evaluator_step = ( last_run.steps["train_model"], last_run.steps["evaluate_model"], ) trainer_url = trainer_step.run_metadata["experiment_tracker_url"].value evaluator_url = evaluator_step.run_metadata["experiment_tracker_url"].value print(f"URL for trainer step: {trainer_url}") print(f"URL for evaluator step: {evaluator_url}") ```
#### Additional configuration For additional configuration of the Comet experiment tracker, you can pass `CometExperimentTrackerSettings` to provide additional tags for your experiments: ```python from zenml.integrations.comet.flavors.comet_experiment_tracker_flavor import ( CometExperimentTrackerSettings, ) comet_settings = CometExperimentTrackerSettings( tags=["some_tag"], run_name="", settings={}, ) @step( experiment_tracker="", settings={ "experiment_tracker": comet_settings } ) def my_step(): ... ``` Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-comet/#zenml.integrations.comet.flavors.comet_experiment_tracker_flavor.CometExperimentTrackerSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings.
ZenML Scarf
================ File: docs/book/component-guide/experiment-trackers/custom.md ================ --- description: Learning how to develop a custom experiment tracker. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a custom experiment tracker {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} {% hint style="warning" %} **Base abstraction in progress!** We are actively working on the base abstraction for the Experiment Tracker, which will be available soon. As a result, their extension is not recommended at the moment. When you are selecting an Experiment Tracker for your stack, you can use one of [the existing flavors](./experiment-trackers.md#experiment-tracker-flavors). If you need to implement your own Experiment Tracker flavor, you can still do so, but keep in mind that you may have to refactor it when the base abstraction is released. {% endhint %} ### Build your own custom experiment tracker If you want to create your own custom flavor for an experiment tracker, you can follow the following steps: 1. Create a class that inherits from the `BaseExperimentTracker` class and implements the abstract methods. 2. If you need any configuration, create a class that inherits from the `BaseExperimentTrackerConfig` class and add your configuration parameters. 3. Bring both the implementation and the configuration together by inheriting from the `BaseExperimentTrackerFlavor` class. Once you are done with the implementation, you can register it through the CLI. Please ensure you **point to the flavor class via dot notation**: ```shell zenml experiment-tracker flavor register ``` For example, if your flavor class `MyExperimentTrackerFlavor` is defined in `flavors/my_flavor.py`, you'd register it by doing: ```shell zenml experiment-tracker flavor register flavors.my_flavor.MyExperimentTrackerFlavor ``` {% hint style="warning" %} ZenML resolves the flavor class by taking the path where you initialized zenml (via `zenml init`) as the starting point of resolution. Therefore, please ensure you follow [the best practice](../../how-to/infrastructure-deployment/infrastructure-as-code/best-practices.md) of initializing zenml at the root of your repository. If ZenML does not find an initialized ZenML repository in any parent directory, it will default to the current working directory, but usually, it's better to not have to rely on this mechanism and initialize zenml at the root. {% endhint %} Afterward, you should see the new flavor in the list of available flavors: ```shell zenml experiment-tracker flavor list ``` {% hint style="warning" %} It is important to draw attention to when and how these base abstractions are coming into play in a ZenML workflow. * The **CustomExperimentTrackerFlavor** class is imported and utilized upon the creation of the custom flavor through the CLI. * The **CustomExperimentTrackerConfig** class is imported when someone tries to register/update a stack component with this custom flavor. Especially, during the registration process of the stack component, the config will be used to validate the values given by the user. As `Config` objects are inherently `pydantic` objects, you can also add your own custom validators here. * The **CustomExperimentTracker** only comes into play when the component is ultimately in use. The design behind this interaction lets us separate the configuration of the flavor from its implementation. This way we can register flavors and components even when the major dependencies behind their implementation are not installed in our local setting (assuming the `CustomExperimentTrackerFlavor` and the `CustomExperimentTrackerConfig` are implemented in a different module/path than the actual `CustomExperimentTracker`). {% endhint %}
ZenML Scarf
================ File: docs/book/component-guide/experiment-trackers/experiment-trackers.md ================ --- description: Logging and visualizing ML experiments. icon: clipboard --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Experiment Trackers Experiment trackers let you track your ML experiments by logging extended information about your models, datasets, metrics, and other parameters and allowing you to browse them, visualize them and compare them between runs. In the ZenML world, every pipeline run is considered an experiment, and ZenML facilitates the storage of experiment results through Experiment Tracker stack components. This establishes a clear link between pipeline runs and experiments. Related concepts: * the Experiment Tracker is an optional type of Stack Component that needs to be registered as part of your ZenML [Stack](../../user-guide/production-guide/understand-stacks.md). * ZenML already provides versioning and tracking for the pipeline artifacts by storing artifacts in the [Artifact Store](../artifact-stores/artifact-stores.md). ### When to use it ZenML already records information about the artifacts circulated through your pipelines by means of the mandatory [Artifact Store](../artifact-stores/artifact-stores.md). However, these ZenML mechanisms are meant to be used programmatically and can be more difficult to work with without a visual interface. Experiment Trackers on the other hand are tools designed with usability in mind. They include extensive UIs providing users with an interactive and intuitive interface that allows them to browse and visualize the information logged during the ML pipeline runs. You should add an Experiment Tracker to your ZenML stack and use it when you want to augment ZenML with the visual features provided by experiment tracking tools. ### How they experiment trackers slot into the stack Here is an architecture diagram that shows how experiment trackers fit into the overall story of a remote stack. ![Experiment Tracker](../../.gitbook/assets/Remote_with_exp_tracker.png) #### Experiment Tracker Flavors Experiment Trackers are optional stack components provided by integrations: | Experiment Tracker | Flavor | Integration | Notes | |------------------------------------|-----------|-------------|-------------------------------------------------------------------------------------------------| | [Comet](comet.md) | `comet` | `comet` | Add Comet experiment tracking and visualization capabilities to your ZenML pipelines | | [MLflow](mlflow.md) | `mlflow` | `mlflow` | Add MLflow experiment tracking and visualization capabilities to your ZenML pipelines | | [Neptune](neptune.md) | `neptune` | `neptune` | Add Neptune experiment tracking and visualization capabilities to your ZenML pipelines | | [Weights & Biases](wandb.md) | `wandb` | `wandb` | Add Weights & Biases experiment tracking and visualization capabilities to your ZenML pipelines | | [Custom Implementation](custom.md) | _custom_ | | _custom_ | If you would like to see the available flavors of Experiment Tracker, you can use the command: ```shell zenml experiment-tracker flavor list ``` ### How to use it Every Experiment Tracker has different capabilities and uses a different way of logging information from your pipeline steps, but it generally works as follows: * first, you have to configure and add an Experiment Tracker to your ZenML stack * next, you have to explicitly enable the Experiment Tracker for individual steps in your pipeline by decorating them with the included decorator * in your steps, you have to explicitly log information (e.g. models, metrics, data) to the Experiment Tracker same as you would if you were using the tool independently of ZenML * finally, you can access the Experiment Tracker UI to browse and visualize the information logged during your pipeline runs. You can use the following code snippet to get the URL of the experiment tracker UI for the experiment linked to a certain step of your pipeline run: ```python from zenml.client import Client pipeline_run = Client().get_pipeline_run("") step = pipeline_run.steps[""] experiment_tracker_url = step.run_metadata["experiment_tracker_url"].value ``` {% hint style="info" %} Experiment trackers will automatically declare runs as failed if the corresponding ZenML pipeline step fails. {% endhint %} Consult the documentation for the particular [Experiment Tracker flavor](experiment-trackers.md#experiment-tracker-flavors) that you plan on using or are using in your stack for detailed information about how to use it in your ZenML pipelines.
ZenML Scarf
================ File: docs/book/component-guide/experiment-trackers/mlflow.md ================ --- description: Logging and visualizing experiments with MLflow. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # MLflow The MLflow Experiment Tracker is an [Experiment Tracker](./experiment-trackers.md) flavor provided with the MLflow ZenML integration that uses [the MLflow tracking service](https://mlflow.org/docs/latest/tracking.html) to log and visualize information from your pipeline steps (e.g. models, parameters, metrics). ## When would you want to use it? [MLflow Tracking](https://www.mlflow.org/docs/latest/tracking.html) is a very popular tool that you would normally use in the iterative ML experimentation phase to track and visualize experiment results. That doesn't mean that it cannot be repurposed to track and visualize the results produced by your automated pipeline runs, as you make the transition toward a more production-oriented workflow. You should use the MLflow Experiment Tracker: * if you have already been using MLflow to track experiment results for your project and would like to continue doing so as you are incorporating MLOps workflows and best practices in your project through ZenML. * if you are looking for a more visually interactive way of navigating the results produced from your ZenML pipeline runs (e.g. models, metrics, datasets) * if you or your team already have a shared MLflow Tracking service deployed somewhere on-premise or in the cloud, and you would like to connect ZenML to it to share the artifacts and metrics logged by your pipelines You should consider one of the other [Experiment Tracker flavors](./experiment-trackers.md#experiment-tracker-flavors) if you have never worked with MLflow before and would rather use another experiment tracking tool that you are more familiar with. ## How do you configure it? The MLflow Experiment Tracker flavor is provided by the MLflow ZenML integration, you need to install it on your local machine to be able to register an MLflow Experiment Tracker and add it to your stack: ```shell zenml integration install mlflow -y ``` The MLflow Experiment Tracker can be configured to accommodate the following [MLflow deployment scenarios](https://mlflow.org/docs/latest/tracking.html#common-setups): * [Localhost (default)](https://mlflow.org/docs/latest/tracking.html#common-setups) and [Local Tracking with Local Database](https://mlflow.org/docs/latest/tracking/tutorials/local-database.html): This scenario requires that you use a [local Artifact Store](../artifact-stores/local.md) alongside the MLflow Experiment Tracker in your ZenML stack. The local Artifact Store comes with limitations regarding what other types of components you can use in the same stack. This scenario should only be used to run ZenML locally and is not suitable for collaborative and production settings. No parameters need to be supplied when configuring the MLflow Experiment Tracker, e.g: ```shell # Register the MLflow experiment tracker zenml experiment-tracker register mlflow_experiment_tracker --flavor=mlflow # Register and set a stack with the new experiment tracker zenml stack register custom_stack -e mlflow_experiment_tracker ... --set ``` * [Remote Experiment Tracking with MLflow Tracking Server](https://mlflow.org/docs/latest/tracking/tutorials/remote-server.html): This scenario assumes that you have already deployed an MLflow Tracking Server enabled with proxied artifact storage access. There is no restriction regarding what other types of components it can be combined with. This option requires [authentication-related parameters](mlflow.md#authentication-methods) to be configured for the MLflow Experiment Tracker. {% hint style="warning" %} Due to a [critical severity vulnerability](https://github.com/advisories/GHSA-xg73-94fp-g449) found in older versions of MLflow, we recommend using MLflow version 2.2.1 or higher. {% endhint %} * [Databricks scenario](https://www.databricks.com/product/managed-mlflow): This scenario assumes that you have a Databricks workspace, and you want to use the managed MLflow Tracking server it provides. This option requires [authentication-related parameters](mlflow.md#authentication-methods) to be configured for the MLflow Experiment Tracker. ### Authentication Methods You need to configure the following credentials for authentication to a remote MLflow tracking server: * `tracking_uri`: The URL pointing to the MLflow tracking server. If using an MLflow Tracking Server managed by Databricks, then the value of this attribute should be `"databricks"`. * `tracking_username`: Username for authenticating with the MLflow tracking server. * `tracking_password`: Password for authenticating with the MLflow tracking server. * `tracking_token` (in place of `tracking_username` and `tracking_password`): Token for authenticating with the MLflow tracking server. * `tracking_insecure_tls` (optional): Set to skip verifying the MLflow tracking server SSL certificate. * `databricks_host`: The host of the Databricks workspace with the MLflow-managed server to connect to. This is only required if the `tracking_uri` value is set to `"databricks"`. More information: [Access the MLflow tracking server from outside Databricks](https://docs.databricks.com/applications/mlflow/access-hosted-tracking-server.html) Either `tracking_token` or `tracking_username` and `tracking_password` must be specified. {% tabs %} {% tab title="Basic Authentication" %} This option configures the credentials for the MLflow tracking service directly as stack component attributes. {% hint style="warning" %} This is not recommended for production settings as the credentials won't be stored securely and will be clearly visible in the stack configuration. {% endhint %} ```shell # Register the MLflow experiment tracker zenml experiment-tracker register mlflow_experiment_tracker --flavor=mlflow \ --tracking_uri= --tracking_token= # You can also register it like this: # zenml experiment-tracker register mlflow_experiment_tracker --flavor=mlflow \ # --tracking_uri= --tracking_username= --tracking_password= # Register and set a stack with the new experiment tracker zenml stack register custom_stack -e mlflow_experiment_tracker ... --set ``` {% endtab %} {% tab title="ZenML Secret (Recommended)" %} This method requires you to [configure a ZenML secret](../../how-to/project-setup-and-management/interact-with-secrets.md) to store the MLflow tracking service credentials securely. You can create the secret using the `zenml secret create` command: ```shell # Create a secret called `mlflow_secret` with key-value pairs for the # username and password to authenticate with the MLflow tracking server zenml secret create mlflow_secret \ --username= \ --password= ``` Once the secret is created, you can use it to configure the MLflow Experiment Tracker: ```shell # Reference the username and password in our experiment tracker component zenml experiment-tracker register mlflow \ --flavor=mlflow \ --tracking_username={{mlflow_secret.username}} \ --tracking_password={{mlflow_secret.password}} \ ... ``` {% hint style="info" %} Read more about [ZenML Secrets](../../how-to/project-setup-and-management/interact-with-secrets.md) in the ZenML documentation. {% endhint %} {% endtab %} {% endtabs %} For more, up-to-date information on the MLflow Experiment Tracker implementation and its configuration, you can have a look at [the SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-mlflow/#zenml.integrations.mlflow.experiment\_trackers.mlflow\_experiment\_tracker) . ## How do you use it? To be able to log information from a ZenML pipeline step using the MLflow Experiment Tracker component in the active stack, you need to enable an experiment tracker using the `@step` decorator. Then use MLflow's logging or auto-logging capabilities as you would normally do, e.g.: ```python import mlflow @step(experiment_tracker="") def tf_trainer( x_train: np.ndarray, y_train: np.ndarray, ) -> tf.keras.Model: """Train a neural net from scratch to recognize MNIST digits return our model or the learner""" # compile model mlflow.tensorflow.autolog() # train model # log additional information to MLflow explicitly if needed mlflow.log_param(...) mlflow.log_metric(...) mlflow.log_artifact(...) return model ``` {% hint style="info" %} Instead of hardcoding an experiment tracker name, you can also use the [Client](../../reference/python-client.md) to dynamically use the experiment tracker of your active stack: ```python from zenml.client import Client experiment_tracker = Client().active_stack.experiment_tracker @step(experiment_tracker=experiment_tracker.name) def tf_trainer(...): ... ``` {% endhint %} ### MLflow UI MLflow comes with its own UI that you can use to find further details about your tracked experiments. You can find the URL of the MLflow experiment linked to a specific ZenML run via the metadata of the step in which the experiment tracker was used: ```python from zenml.client import Client last_run = client.get_pipeline("").last_run trainer_step = last_run.get_step("") tracking_url = trainer_step.run_metadata["experiment_tracker_url"].value print(tracking_url) ``` This will be the URL of the corresponding experiment in your deployed MLflow instance, or a link to the corresponding mlflow experiment file if you are using local MLflow. {% hint style="info" %} If you are using local MLflow, you can use the `mlflow ui` command to start MLflow at [`localhost:5000`](http://localhost:5000/) where you can then explore the UI in your browser. ```bash mlflow ui --backend-store-uri ``` {% endhint %} ### Additional configuration For additional configuration of the MLflow experiment tracker, you can pass `MLFlowExperimentTrackerSettings` to create nested runs or add additional tags to your MLflow runs: ```python import mlflow from zenml.integrations.mlflow.flavors.mlflow_experiment_tracker_flavor import MLFlowExperimentTrackerSettings mlflow_settings = MLFlowExperimentTrackerSettings( nested=True, tags={"key": "value"} ) @step( experiment_tracker="", settings={ "experiment_tracker": mlflow_settings } ) def step_one( data: np.ndarray, ) -> np.ndarray: ... ``` Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-mlflow/#zenml.integrations.mlflow.flavors.mlflow_experiment_tracker_flavor.MLFlowExperimentTrackerSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings.
ZenML Scarf
================ File: docs/book/component-guide/experiment-trackers/neptune.md ================ --- description: Logging and visualizing experiments with neptune.ai --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Neptune The Neptune Experiment Tracker is an [Experiment Tracker](./experiment-trackers.md) flavor provided with the Neptune-ZenML integration that uses [neptune.ai](https://neptune.ai/product/experiment-tracking) to log and visualize information from your pipeline steps (e.g. models, parameters, metrics). ### When would you want to use it? [Neptune](https://neptune.ai/product/experiment-tracking) is a popular tool that you would normally use in the iterative ML experimentation phase to track and visualize experiment results or as a model registry for your production-ready models. Neptune can also track and visualize the results produced by your automated pipeline runs, as you make the transition towards a more production-oriented workflow. You should use the Neptune Experiment Tracker: * if you have already been using neptune.ai to track experiment results for your project and would like to continue doing so as you are incorporating MLOps workflows and best practices in your project through ZenML. * if you are looking for a more visually interactive way of navigating the results produced from your ZenML pipeline runs (e.g. models, metrics, datasets) * if you would like to connect ZenML to neptune.ai to share the artifacts and metrics logged by your pipelines with your team, organization, or external stakeholders You should consider one of the other [Experiment Tracker flavors](./experiment-trackers.md#experiment-tracker-flavors) if you have never worked with neptune.ai before and would rather use another experiment tracking tool that you are more familiar with. ### How do you deploy it? The Neptune Experiment Tracker flavor is provided by the Neptune-ZenML integration. You need to install it on your local machine to be able to register the Neptune Experiment Tracker and add it to your stack: ```shell zenml integration install neptune -y ``` The Neptune Experiment Tracker needs to be configured with the credentials required to connect to Neptune using an API token. ### Authentication Methods You need to configure the following credentials for authentication to Neptune: * `api_token`: [API key token](https://docs.neptune.ai/setup/setting_api_token) of your Neptune account. You can create a free Neptune account [here](https://app.neptune.ai/register). If left blank, Neptune will attempt to retrieve the token from your environment variables. * `project`: The name of the project where you're sending the new run, in the form "workspace-name/project-name". If the project is not specified, Neptune will attempt to retrieve it from your environment variables. {% tabs %} {% tab title="ZenML Secret (Recommended)" %} This method requires you to [configure a ZenML secret](../../how-to/project-setup-and-management/interact-with-secrets.md) to store the Neptune tracking service credentials securely. You can create the secret using the `zenml secret create` command: ```shell zenml secret create neptune_secret --api_token= ``` Once the secret is created, you can use it to configure the `neptune` Experiment Tracker: ```shell # Reference the project and api-token in our experiment tracker component zenml experiment-tracker register neptune_experiment_tracker \ --flavor=neptune \ --project= \ --api_token={{neptune_secret.api_token}} ... # Register and set a stack with the new experiment tracker zenml stack register neptune_stack -e neptune_experiment_tracker ... --set ``` {% hint style="info" %} Read more about [ZenML Secrets](../../how-to/project-setup-and-management/interact-with-secrets.md) in the ZenML documentation. {% endhint %} {% endtab %} {% tab title="Basic Authentication" %} This option configures the credentials for neptune.ai directly as stack component attributes. {% hint style="warning" %} This is not recommended for production settings as the credentials won't be stored securely and will be clearly visible in the stack configuration. {% endhint %} ```shell # Register the Neptune experiment tracker zenml experiment-tracker register neptune_experiment_tracker --flavor=neptune \ --project= --api_token= # Register and set a stack with the new experiment tracker zenml stack register neptune_stack -e neptune_experiment_tracker ... --set ``` {% endtab %} {% endtabs %} For more, up-to-date information on the Neptune Experiment Tracker implementation and its configuration, you can have a look at [the SDK docs](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-neptune/#zenml.integrations.neptune.experiment_trackers.neptune_experiment_tracker) . ### How do you use it? To log information from a ZenML pipeline step using the Neptune Experiment Tracker component in the active stack, you need to enable an experiment tracker using the `@step` decorator. Then fetch the [Neptune run object](https://docs.neptune.ai/api/run/) and use logging capabilities as you would normally do. For example: ```python from zenml.integrations.neptune.experiment_trackers.run_state import ( get_neptune_run ) from neptune.utils import stringify_unsupported from zenml import get_step_context from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.datasets import load_iris from zenml import pipeline, step from zenml.client import Client from zenml.integrations.neptune.experiment_trackers import NeptuneExperimentTracker # Get the experiment tracker from the active stack experiment_tracker: NeptuneExperimentTracker = Client().active_stack.experiment_tracker @step(experiment_tracker="neptune_experiment_tracker") def train_model() -> SVC: iris = load_iris() X_train, _, y_train, _ = train_test_split( iris.data, iris.target, test_size=0.2, random_state=42 ) params = { "kernel": "rbf", "C": 1.0, } model = SVC(**params) model.fit(X_train, y_train) # Log the model to Neptune neptune_run = get_neptune_run() neptune_run["parameters"] = params return model ``` {% hint style="info" %} Instead of hardcoding an experiment tracker name, you can also use the [Client](../../reference/python-client.md) to dynamically use the experiment tracker of your active stack: ```python from zenml.client import Client experiment_tracker = Client().active_stack.experiment_tracker @step(experiment_tracker=experiment_tracker.name) def tf_trainer(...): ... ``` {% endhint %} #### Logging ZenML pipeline and step metadata to the Neptune run You can use the `get_step_context` method to log some ZenML metadata in your Neptune run: ```python from zenml import get_step_context from zenml.integrations.neptune.experiment_trackers.run_state import ( get_neptune_run ) from neptune.utils import stringify_unsupported @step(experiment_tracker="neptune_tracker") def my_step(): neptune_run = get_neptune_run() context = get_step_context() neptune_run["pipeline_metadata"] = stringify_unsupported( context.pipeline_run.get_metadata().dict() ) neptune_run[f"step_metadata/{context.step_name}"] = stringify_unsupported( context.step_run.get_metadata().dict() ) ... ``` #### Adding tags to your Neptune run You can pass a set of tags to the Neptune run by using the `NeptuneExperimentTrackerSettings` class, like in the example below: ```python import numpy as np import tensorflow as tf from zenml import step from zenml.integrations.neptune.experiment_trackers.run_state import ( get_neptune_run, ) from zenml.integrations.neptune.flavors import NeptuneExperimentTrackerSettings neptune_settings = NeptuneExperimentTrackerSettings(tags={"keras", "mnist"}) @step( experiment_tracker="", settings={ "experiment_tracker": neptune_settings } ) def my_step( x_test: np.ndarray, y_test: np.ndarray, model: tf.keras.Model, ) -> float: """Log metadata to Neptune run""" neptune_run = get_neptune_run() ... ``` Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-neptune/#zenml.integrations.neptune.flavors.neptune_experiment_tracker_flavor.NeptuneExperimentTrackerSettings) for a full list of available attributes ## Neptune UI Neptune comes with a web-based UI that you can use to find further details about your tracked experiments. You can find the URL of the Neptune run linked to a specific ZenML run printed on the console whenever a Neptune run is initialized. You can also find it in the dashboard in the metadata tab of any step that has used the tracker:

A pipeline with a Neptine run linked as metadata

Each pipeline run will be logged as a separate experiment run in Neptune, which you can inspect in the Neptune UI.

A list of Neptune runs from ZenML pipelines

Clicking on one run will reveal further metadata logged within the step:

Details of a Neptune run via a ZenML pipeline

## Full Code Example This section shows an end to end run with the ZenML Neptune integration.
Code Example of this Section ```python from zenml.integrations.neptune.experiment_trackers.run_state import ( get_neptune_run ) from neptune.utils import stringify_unsupported from zenml import get_step_context from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris from sklearn.svm import SVC from sklearn.metrics import accuracy_score from zenml import pipeline, step from zenml.client import Client from zenml.integrations.neptune.experiment_trackers import NeptuneExperimentTracker import neptune.integrations.sklearn as npt_utils # Get the experiment tracker from the active stack experiment_tracker: NeptuneExperimentTracker = Client().active_stack.experiment_tracker @step(experiment_tracker=experiment_tracker.name) def train_model() -> SVC: iris = load_iris() X_train, _, y_train, _ = train_test_split( iris.data, iris.target, test_size=0.2, random_state=42 ) params = { "kernel": "rbf", "C": 1.0, } model = SVC(**params) model.fit(X_train, y_train) # Log parameters and model to Neptune neptune_run = get_neptune_run() neptune_run["parameters"] = params neptune_run["estimator/pickled-model"] = npt_utils.get_pickled_model(model) return model @step(experiment_tracker=experiment_tracker.name) def evaluate_model(model: SVC): iris = load_iris() _, X_test, _, y_test = train_test_split( iris.data, iris.target, test_size=0.2, random_state=42 ) y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) neptune_run = get_neptune_run() context = get_step_context() # Log metadata using Neptune neptune_run["zenml_metadata/pipeline_metadata"] = stringify_unsupported( context.pipeline_run.get_metadata().model_dump() ) neptune_run[f"zenml_metadata/{context.step_name}"] = stringify_unsupported( context.step_run.get_metadata().model_dump() ) # Log accuracy metric to Neptune neptune_run["metrics/accuracy"] = accuracy return accuracy @pipeline def ml_pipeline(): model = train_model() accuracy = evaluate_model(model) if __name__ == "__main__": from zenml.integrations.neptune.flavors import NeptuneExperimentTrackerSettings neptune_settings = NeptuneExperimentTrackerSettings( tags={"regression", "sklearn"} ) ml_pipeline.with_options(settings={"experiment_tracker": neptune_settings})() ```
## Further reading Check [Neptune's docs](https://docs.neptune.ai/integrations/zenml/) for further information on how to use this integration and Neptune in general.
ZenML Scarf
================ File: docs/book/component-guide/experiment-trackers/vertexai.md ================ --- description: Logging and visualizing experiments with Vertex AI Experiment Tracker. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Vertex AI Experiment Tracker The Vertex AI Experiment Tracker is an [Experiment Tracker](./experiment-trackers.md) flavor provided with the Vertex AI ZenML integration. It uses the [Vertex AI tracking service](https://cloud.google.com/vertex-ai/docs/experiments/intro-vertex-ai-experiments) to log and visualize information from your pipeline steps (e.g., models, parameters, metrics). ## When would you want to use it? [Vertex AI Experiment Tracker](https://cloud.google.com/vertex-ai/docs/experiments/intro-vertex-ai-experiments) is a managed service by Google Cloud that you would normally use in the iterative ML experimentation phase to track and visualize experiment results. That doesn't mean that it cannot be repurposed to track and visualize the results produced by your automated pipeline runs, as you make the transition toward a more production-oriented workflow. You should use the Vertex AI Experiment Tracker: * if you have already been using Vertex AI to track experiment results for your project and would like to continue doing so as you are incorporating MLOps workflows and best practices in your project through ZenML. * if you are looking for a more visually interactive way of navigating the results produced from your ZenML pipeline runs (e.g. models, metrics, datasets) * if you are building machine learning workflows in the Google Cloud ecosystem and want a managed experiment tracking solution tightly integrated with other Google Cloud services, Vertex AI is a great choice You should consider one of the other [Experiment Tracker flavors](./experiment-trackers.md#experiment-tracker-flavors) if you have never worked with Vertex AI before and would rather use another experiment tracking tool that you are more familiar with, or if you are not using GCP or using other cloud providers. ## How do you configure it? The Vertex AI Experiment Tracker flavor is provided by the GCP ZenML integration, you need to install it on your local machine to be able to register a Vertex AI Experiment Tracker and add it to your stack: ```shell zenml integration install gcp -y ``` ### Configuration Options To properly register the Vertex AI Experiment Tracker, you can provide several configuration options tailored to your needs. Here are the main configurations you may want to set: * `project`: Optional. GCP project name. If `None` it will be inferred from the environment. * `location`: Optional. GCP location where your experiments will be created. If not set defaults to us-central1. * `staging_bucket`: Optional. The default staging bucket to use to stage artifacts. In the form gs://... * `service_account_path`: Optional. A path to the service account credential json file to be used to interact with Vertex AI Experiment Tracker. Please check the [Authentication Methods](vertexai.md#authentication-methods) chapter for more details. With the project, location and staging_bucket, registering the Vertex AI Experiment Tracker can be done as follows: ```shell # Register the Vertex AI Experiment Tracker zenml experiment-tracker register vertex_experiment_tracker \ --flavor=vertex \ --project= \ --location= \ --staging_bucket=gs:// # Register and set a stack with the new experiment tracker zenml stack register custom_stack -e vertex_experiment_tracker ... --set ``` ### Authentication Methods Integrating and using a Vertex AI Experiment Tracker in your pipelines is not possible without employing some form of authentication. If you're looking for a quick way to get started locally, you can use the _Implicit Authentication_ method. However, the recommended way to authenticate to the Google Cloud Platform is through a [GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md). This is particularly useful if you are configuring ZenML stacks that combine the Vertex AI Experiment Tracker with other remote stack components also running in GCP. > **Note**: Regardless of your chosen authentication method, you must grant your account the necessary roles to use Vertex AI Experiment Tracking. > * `roles/aiplatform.user` role on your project, which allows you to create, manage, and track your experiments within Vertex AI. > * `roles/storage.objectAdmin` role on your GCS bucket, granting the ability to read and write experiment artifacts, such as models and datasets, to the storage bucket. {% tabs %} {% tab title="Implicit Authentication" %} This configuration method assumes that you have authenticated locally to GCP using the [`gcloud` CLI](https://cloud.google.com/sdk/gcloud) (e.g., by running gcloud auth login). > **Note**: This method is quick for local setups but is unsuitable for team collaborations or production environments due to its lack of portability. We can then register the experiment tracker as follows: ```shell # Register the Vertex AI Experiment Tracker zenml experiment-tracker register \ --flavor=vertex \ --project= \ --location= \ --staging_bucket=gs:// # Register and set a stack with the new experiment tracker zenml stack register custom_stack -e vertex_experiment_tracker ... --set ``` {% endtab %} {% tab title="GCP Service Connector (recommended)" %} To set up the Vertex AI Experiment Tracker to authenticate to GCP, it is recommended to leverage the many features provided by the [GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) such as auto-configuration, best security practices regarding long-lived credentials and reusing the same credentials across multiple stack components. If you don't already have a GCP Service Connector configured in your ZenML deployment, you can register one using the interactive CLI command. You have the option to configure a GCP Service Connector that can be used to access more than one type of GCP resource: ```sh # Register a GCP Service Connector interactively zenml service-connector register --type gcp -i ``` After having set up or decided on a GCP Service Connector to use, you can register the Vertex AI Experiment Tracker as follows: ```shell # Register the Vertex AI Experiment Tracker zenml experiment-tracker register \ --flavor=vertex \ --project= \ --location= \ --staging_bucket=gs:// zenml experiment-tracker connect --connector # Register and set a stack with the new experiment tracker zenml stack register custom_stack -e vertex_experiment_tracker ... --set ``` {% endtab %} {% tab title="GCP Credentials" %} When you register the Vertex AI Experiment Tracker, you can [generate a GCP Service Account Key](https://cloud.google.com/docs/authentication/application-default-credentials#attached-sa), store it in a [ZenML Secret](../../getting-started/deploying-zenml/secret-management.md) and then reference it in the Experiment Tracker configuration. This method has some advantages over the implicit authentication method: * you don't need to install and configure the GCP CLI on your host * you don't need to care about enabling your other stack components (orchestrators, step operators and model deployers) to have access to the experiment tracker through GCP Service Accounts and Workload Identity * you can combine the Vertex AI Experiment Tracker with other stack components that are not running in GCP For this method, you need to [create a user-managed GCP service account](https://cloud.google.com/iam/docs/service-accounts-create) and then [create a service account key](https://cloud.google.com/iam/docs/keys-create-delete#creating). With the service account key downloaded to a local file, you can register a ZenML secret and reference it in the Vertex AI Experiment Tracker configuration as follows: ```shell # Register the Vertex AI Experiment Tracker and reference the ZenML secret zenml experiment-tracker register \ --flavor=vertex \ --project= \ --location= \ --staging_bucket=gs:// \ --service_account_path=path/to/service_account_key.json # Register and set a stack with the new experiment tracker zenml experiment-tracker connect --connector ``` {% endtab %} {% endtabs %} ## How do you use it? To be able to log information from a ZenML pipeline step using the Vertex AI Experiment Tracker component in the active stack, you need to enable an experiment tracker using the `@step` decorator. Then use Vertex AI's logging or auto-logging capabilities as you would normally do, e.g. Here are two examples demonstrating how to use the experiment tracker: ### Example 1: Logging Metrics Using Built-in Methods This example demonstrates how to log time-series metrics using `aiplatform.log_time_series_metrics` from within a Keras callback, and using `aiplatform.log_metrics` to log specific metrics and `aiplatform.log_params` to log experiment parameters. The logged metrics can then be visualized in the UI of Vertex AI Experiment Tracker and integrated TensorBoard instance. > **Note:** To use the autologging functionality, ensure that the google-cloud-aiplatform library is installed with the Autologging extension. You can do this by running the following command: > ```bash > pip install google-cloud-aiplatform[autologging] > ``` ```python from google.cloud import aiplatform class VertexAICallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): logs = logs or {} metrics = {key: value for key, value in logs.items() if isinstance(value, (int, float))} aiplatform.log_time_series_metrics(metrics=metrics, step=epoch) @step(experiment_tracker="") def train_model( config: TrainerConfig, x_train: np.ndarray, y_train: np.ndarray, x_val: np.ndarray, y_val: np.ndarray, ): aiplatform.autolog() ... # Train the model, using the custom callback to log metrics into experiment tracker model.fit( x_train, y_train, validation_data=(x_test, y_test), epochs=config.epochs, batch_size=config.batch_size, callbacks=[VertexAICallback()] ) ... # Log specific metrics and parameters aiplatform.log_metrics(...) aiplatform.log_params(...) ``` ### Example 2: Uploading TensorBoard Logs This example demonstrates how to use an integrated TensorBoard instance to directly upload training logs. This is particularly useful if you're already using TensorBoard in your projects and want to benefit from its detailed visualizations during training. You can initiate the upload using `aiplatform.start_upload_tb_log` and conclude it with `aiplatform.end_upload_tb_log`. Similar to the first example, you can also log specific metrics and parameters directly. > **Note:** To use TensorBoard logging functionality, ensure you have the `google-cloud-aiplatform` library installed with the TensorBoard extension. You can install it using the following command: > ```bash > pip install google-cloud-aiplatform[tensorboard] > ``` ```python from google.cloud import aiplatform @step(experiment_tracker="") def train_model( config: TrainerConfig, gcs_path: str, x_train: np.ndarray, y_train: np.ndarray, x_val: np.ndarray, y_val: np.ndarray, ): # get current experiment and run names experiment_tracker = Client().active_stack.experiment_tracker experiment_name = experiment_tracker.experiment_name experiment_run_name = experiment_tracker.run_name # define a TensorBoard callback, logs are written to gcs_path tensorboard_callback = tf.keras.callbacks.TensorBoard( log_dir=gcs_path, histogram_freq=1 ) # start the TensorBoard log upload aiplatform.start_upload_tb_log( tensorboard_experiment_name=experiment_name, logdir=gcs_path, run_name_prefix=f"{experiment_run_name}_", ) model.fit( x_train, y_train, validation_data=(x_test, y_test), epochs=config.epochs, batch_size=config.batch_size, ) ... # end the TensorBoard log upload aiplatform.end_upload_tb_log() aiplatform.log_metrics(...) aiplatform.log_params(...) ``` {% hint style="info" %} Instead of hardcoding an experiment tracker name, you can also use the [Client](../../reference/python-client.md) to dynamically use the experiment tracker of your active stack: ```python from zenml.client import Client experiment_tracker = Client().active_stack.experiment_tracker @step(experiment_tracker=experiment_tracker.name) def tf_trainer(...): ... ``` {% endhint %} ### Experiment Tracker UI You can find the URL of the Vertex AI experiment linked to a specific ZenML run via the metadata of the step in which the experiment tracker was used: ```python from zenml.client import Client client = Client() last_run = client.get_pipeline("").last_run trainer_step = last_run.steps.get("") tracking_url = trainer_step.run_metadata["experiment_tracker_url"].value print(tracking_url) ``` This will be the URL of the corresponding experiment in Vertex AI Experiment Tracker. Below are examples of the UI for the Vertex AI Experiment Tracker and the integrated TensorBoard instance. **Vertex AI Experiment Tracker UI** ![VerteAI UI](../../.gitbook/assets/vertexai_experiment_tracker_ui.png) **TensorBoard UI** ![TensorBoard UI](../../.gitbook/assets/vertexai_experiment_tracker_tb.png) ### Additional configuration For additional configuration of the Vertex AI Experiment Tracker, you can pass `VertexExperimentTrackerSettings` to specify an experiment name or choose previously created TensorBoard instance. > **Note**: By default, Vertex AI will use the default TensorBoard instance in your project if you don't explicitly specify one. ```python import mlflow from zenml.integrations.gcp.flavors.vertex_experiment_tracker_flavor import VertexExperimentTrackerSettings vertexai_settings = VertexExperimentTrackerSettings( experiment="", experiment_tensorboard="TENSORBOARD_RESOURCE_NAME" ) @step( experiment_tracker="", settings={"experiment_tracker": vertexai_settings}, ) def step_one( data: np.ndarray, ) -> np.ndarray: ... ``` Check out [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings.
ZenML Scarf
================ File: docs/book/component-guide/experiment-trackers/wandb.md ================ --- description: Logging and visualizing experiments with Weights & Biases. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Weights & Biases The Weights & Biases Experiment Tracker is an [Experiment Tracker](./experiment-trackers.md) flavor provided with the Weights & Biases ZenML integration that uses [the Weights & Biases experiment tracking platform](https://wandb.ai/site/experiment-tracking) to log and visualize information from your pipeline steps (e.g. models, parameters, metrics). ### When would you want to use it? [Weights & Biases](https://wandb.ai/site/experiment-tracking) is a very popular platform that you would normally use in the iterative ML experimentation phase to track and visualize experiment results. That doesn't mean that it cannot be repurposed to track and visualize the results produced by your automated pipeline runs, as you make the transition towards a more production-oriented workflow. You should use the Weights & Biases Experiment Tracker: * if you have already been using Weights & Biases to track experiment results for your project and would like to continue doing so as you are incorporating MLOps workflows and best practices in your project through ZenML. * if you are looking for a more visually interactive way of navigating the results produced from your ZenML pipeline runs (e.g. models, metrics, datasets) * if you would like to connect ZenML to Weights & Biases to share the artifacts and metrics logged by your pipelines with your team, organization, or external stakeholders You should consider one of the other [Experiment Tracker flavors](./experiment-trackers.md#experiment-tracker-flavors) if you have never worked with Weights & Biases before and would rather use another experiment tracking tool that you are more familiar with. ### How do you deploy it? The Weights & Biases Experiment Tracker flavor is provided by the W&B ZenML integration, you need to install it on your local machine to be able to register a Weights & Biases Experiment Tracker and add it to your stack: ```shell zenml integration install wandb -y ``` The Weights & Biases Experiment Tracker needs to be configured with the credentials required to connect to the Weights & Biases platform using one of the [available authentication methods](wandb.md#authentication-methods). #### Authentication Methods You need to configure the following credentials for authentication to the Weights & Biases platform: * `api_key`: Mandatory API key token of your Weights & Biases account. * `project_name`: The name of the project where you're sending the new run. If the project is not specified, the run is put in an "Uncategorized" project. * `entity`: An entity is a username or team name where you're sending runs. This entity must exist before you can send runs there, so make sure to create your account or team in the UI before starting to log runs. If you don't specify an entity, the run will be sent to your default entity, which is usually your username. {% tabs %} {% tab title="Basic Authentication" %} This option configures the credentials for the Weights & Biases platform directly as stack component attributes. {% hint style="warning" %} This is not recommended for production settings as the credentials won't be stored securely and will be clearly visible in the stack configuration. {% endhint %} ```shell # Register the Weights & Biases experiment tracker zenml experiment-tracker register wandb_experiment_tracker --flavor=wandb \ --entity= --project_name= --api_key= # Register and set a stack with the new experiment tracker zenml stack register custom_stack -e wandb_experiment_tracker ... --set ``` {% endtab %} {% tab title="ZenML Secret (Recommended)" %} This method requires you to [configure a ZenML secret](../../how-to/project-setup-and-management/interact-with-secrets.md) to store the Weights & Biases tracking service credentials securely. You can create the secret using the `zenml secret create` command: ```shell zenml secret create wandb_secret \ --entity= \ --project_name= --api_key= ``` Once the secret is created, you can use it to configure the wandb Experiment Tracker: ```shell # Reference the entity, project and api-key in our experiment tracker component zenml experiment-tracker register wandb_tracker \ --flavor=wandb \ --entity={{wandb_secret.entity}} \ --project_name={{wandb_secret.project_name}} \ --api_key={{wandb_secret.api_key}} ... ``` {% hint style="info" %} Read more about [ZenML Secrets](../../how-to/project-setup-and-management/interact-with-secrets.md) in the ZenML documentation. {% endhint %} {% endtab %} {% endtabs %} For more, up-to-date information on the Weights & Biases Experiment Tracker implementation and its configuration, you can have a look at [the SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-wandb/#zenml.integrations.wandb.experiment\_trackers.wandb\_experiment\_tracker) . ### How do you use it? To be able to log information from a ZenML pipeline step using the Weights & Biases Experiment Tracker component in the active stack, you need to enable an experiment tracker using the `@step` decorator. Then use Weights & Biases logging or auto-logging capabilities as you would normally do, e.g.: ```python import wandb from wandb.integration.keras import WandbCallback @step(experiment_tracker="") def tf_trainer( config: TrainerConfig, x_train: np.ndarray, y_train: np.ndarray, x_val: np.ndarray, y_val: np.ndarray, ) -> tf.keras.Model: ... model.fit( x_train, y_train, epochs=config.epochs, validation_data=(x_val, y_val), callbacks=[ WandbCallback( log_evaluation=True, validation_steps=16, validation_data=(x_val, y_val), ) ], ) metric = ... wandb.log({"": metric}) ``` {% hint style="info" %} Instead of hardcoding an experiment tracker name, you can also use the [Client](../../reference/python-client.md) to dynamically use the experiment tracker of your active stack: ```python from zenml.client import Client experiment_tracker = Client().active_stack.experiment_tracker @step(experiment_tracker=experiment_tracker.name) def tf_trainer(...): ... ``` {% endhint %} ### Weights & Biases UI Weights & Biases comes with a web-based UI that you can use to find further details about your tracked experiments. Every ZenML step that uses Weights & Biases should create a separate experiment run which you can inspect in the Weights & Biases UI: ![WandB UI](../../.gitbook/assets/WandBUI.png) You can find the URL of the Weights & Biases experiment linked to a specific ZenML run via the metadata of the step in which the experiment tracker was used: ```python from zenml.client import Client last_run = client.get_pipeline("").last_run trainer_step = last_run.get_step("") tracking_url = trainer_step.run_metadata["experiment_tracker_url"].value print(tracking_url) ``` Or on the ZenML dashboard as metadata of a step that uses the tracker: ![WandB UI](../../.gitbook/assets/wandb_dag.png) Alternatively, you can see an overview of all experiment runs at https://wandb.ai/{ENTITY\_NAME}/{PROJECT\_NAME}/runs/. {% hint style="info" %} The naming convention of each Weights & Biases experiment run is `{pipeline_run_name}_{step_name}` (e.g. `wandb_example_pipeline-25_Apr_22-20_06_33_535737_tf_evaluator`) and each experiment run will be tagged with both `pipeline_name` and `pipeline_run_name`, which you can use to group and filter experiment runs. {% endhint %} #### Additional configuration For additional configuration of the Weights & Biases experiment tracker, you can pass `WandbExperimentTrackerSettings` to overwrite the [wandb.Settings](https://github.com/wandb/client/blob/master/wandb/sdk/wandb\_settings.py#L353) or pass additional tags for your runs: ```python import wandb from zenml.integrations.wandb.flavors.wandb_experiment_tracker_flavor import WandbExperimentTrackerSettings wandb_settings = WandbExperimentTrackerSettings( settings=wandb.Settings(...), tags=["some_tag"] ) @step( experiment_tracker="", settings={ "experiment_tracker": wandb_settings } ) def my_step( x_test: np.ndarray, y_test: np.ndarray, model: tf.keras.Model, ) -> float: """Everything in this step is auto-logged""" ... ``` ## Full Code Example This section shows an end to end run with the ZenML W&B integration.
Code Example of this Section ```python from typing import Tuple from zenml import pipeline, step from zenml.client import Client from zenml.integrations.wandb.flavors.wandb_experiment_tracker_flavor import ( WandbExperimentTrackerSettings, ) from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, Trainer, TrainingArguments, DistilBertForSequenceClassification, ) from datasets import load_dataset, Dataset import numpy as np from sklearn.metrics import accuracy_score, precision_recall_fscore_support import wandb # Get the experiment tracker from the active stack experiment_tracker = Client().active_stack.experiment_tracker @step def prepare_data() -> Tuple[Dataset, Dataset]: dataset = load_dataset("imdb") tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased") def tokenize_function(examples): return tokenizer(examples["text"], padding="max_length", truncation=True) tokenized_datasets = dataset.map(tokenize_function, batched=True) return ( tokenized_datasets["train"].shuffle(seed=42).select(range(1000)), tokenized_datasets["test"].shuffle(seed=42).select(range(100)), ) # Train the model @step(experiment_tracker=experiment_tracker.name) def train_model( train_dataset: Dataset, eval_dataset: Dataset ) -> DistilBertForSequenceClassification: model = AutoModelForSequenceClassification.from_pretrained( "distilbert-base-uncased", num_labels=2 ) training_args = TrainingArguments( output_dir="./results", num_train_epochs=3, per_device_train_batch_size=16, per_device_eval_batch_size=16, warmup_steps=500, weight_decay=0.01, logging_dir="./logs", evaluation_strategy="epoch", logging_steps=100, report_to=["wandb"], ) def compute_metrics(eval_pred): logits, labels = eval_pred predictions = np.argmax(logits, axis=-1) precision, recall, f1, _ = precision_recall_fscore_support( labels, predictions, average="binary" ) acc = accuracy_score(labels, predictions) return {"accuracy": acc, "f1": f1, "precision": precision, "recall": recall} trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=eval_dataset, compute_metrics=compute_metrics, ) trainer.train() # Evaluate the model eval_results = trainer.evaluate() print(f"Evaluation results: {eval_results}") # Log final evaluation results wandb.log({"final_evaluation": eval_results}) return model @pipeline(enable_cache=False) def fine_tuning_pipeline(): train_dataset, eval_dataset = prepare_data() model = train_model(train_dataset, eval_dataset) if __name__ == "__main__": # Run the pipeline wandb_settings = WandbExperimentTrackerSettings( tags=["distilbert", "imdb", "sentiment-analysis"], ) fine_tuning_pipeline.with_options(settings={"experiment_tracker": wandb_settings})() ```
Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-wandb/#zenml.integrations.wandb.flavors.wandb\_experiment\_tracker\_flavor.WandbExperimentTrackerSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings.
ZenML Scarf
================ File: docs/book/component-guide/feature-stores/custom.md ================ --- description: Learning how to develop a custom feature store. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a Custom Feature Store {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} Feature stores allow data teams to serve data via an offline store, and an online low-latency store where data is kept in sync between the two. It also offers a centralized registry where features (and feature schemas) are stored for use within a team or wider organization. {% hint style="warning" %} **Base abstraction in progress!** We are actively working on the base abstraction for the feature stores, which will be available soon. As a result, their extension is not possible at the moment. If you would like to use a feature store in your stack, please check the list of already available feature stores down below. {% endhint %}
ZenML Scarf
================ File: docs/book/component-guide/feature-stores/feast.md ================ --- description: Managing data in Feast feature stores. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Feast Feast (Feature Store) is an operational data system for managing and serving machine learning features to models in production. Feast is able to serve feature data to models from a low-latency online store (for real-time prediction) or from an offline store (for scale-out batch scoring or model training). ### When would you want to use it? There are two core functions that feature stores enable: * access to data from an offline / batch store for training. * access to online data at inference time. Feast integration currently supports your choice of offline data sources for your online feature serving. We encourage users to check out [Feast's documentation](https://docs.feast.dev/) and [guides](https://docs.feast.dev/how-to-guides/) on how to set up your offline and online data sources via the configuration `yaml` file. {% hint style="info" %} COMING SOON: While the ZenML integration has an interface to access online feature store data, it currently is not usable in production settings with deployed models. We will update the docs when we enable this functionality. {% endhint %} ### How to deploy it? ZenML assumes that users already have a Feast feature store that they just need to connect with. If you don't have a feature store yet, follow the [Feast Documentation](https://docs.feast.dev/how-to-guides/feast-snowflake-gcp-aws/deploy-a-feature-store) to deploy one first. To use the feature store as a ZenML stack component, you also need to install the corresponding `feast` integration in ZenML: ```shell zenml integration install feast ``` Now you can register your feature store as a ZenML stack component and add it into a corresponding stack: ```shell zenml feature-store register feast_store --flavor=feast --feast_repo="" zenml stack register ... -f feast_store ``` ### How do you use it? {% hint style="warning" %} Online data retrieval is possible in a local setting, but we don't currently support using the online data serving in the context of a deployed model or as part of model deployment. We will update this documentation as we develop this feature. {% endhint %} Getting features from a registered and active feature store is possible by creating your own step that interfaces into the feature store: ```python from datetime import datetime from typing import Any, Dict, List, Union import pandas as pd from zenml import step from zenml.client import Client @step def get_historical_features( entity_dict: Union[Dict[str, Any], str], features: List[str], full_feature_names: bool = False ) -> pd.DataFrame: """Feast Feature Store historical data step Returns: The historical features as a DataFrame. """ feature_store = Client().active_stack.feature_store if not feature_store: raise DoesNotExistException( "The Feast feature store component is not available. " "Please make sure that the Feast stack component is registered as part of your current active stack." ) params.entity_dict["event_timestamp"] = [ datetime.fromisoformat(val) for val in entity_dict["event_timestamp"] ] entity_df = pd.DataFrame.from_dict(entity_dict) return feature_store.get_historical_features( entity_df=entity_df, features=features, full_feature_names=full_feature_names, ) entity_dict = { "driver_id": [1001, 1002, 1003], "label_driver_reported_satisfaction": [1, 5, 3], "event_timestamp": [ datetime(2021, 4, 12, 10, 59, 42).isoformat(), datetime(2021, 4, 12, 8, 12, 10).isoformat(), datetime(2021, 4, 12, 16, 40, 26).isoformat(), ], "val_to_add": [1, 2, 3], "val_to_add_2": [10, 20, 30], } features = [ "driver_hourly_stats:conv_rate", "driver_hourly_stats:acc_rate", "driver_hourly_stats:avg_daily_trips", "transformed_conv_rate:conv_rate_plus_val1", "transformed_conv_rate:conv_rate_plus_val2", ] @pipeline def my_pipeline(): my_features = get_historical_features(entity_dict, features) ... ``` {% hint style="warning" %} Note that ZenML's use of Pydantic to serialize and deserialize inputs stored in the ZenML metadata means that we are limited to basic data types. Pydantic cannot handle Pandas `DataFrame`s, for example, or `datetime` values, so in the above code you can see that we have to convert them at various points. {% endhint %} For more information and a full list of configurable attributes of the Feast feature store, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-feast/#zenml.integrations.feast.feature\_stores.feast\_feature\_store.FeastFeatureStore) .
ZenML Scarf
================ File: docs/book/component-guide/feature-stores/feature-stores.md ================ --- icon: database description: Managing data in feature stores. --- # Feature Stores Feature stores allow data teams to serve data via an offline store and an online low-latency store where data is kept in sync between the two. It also offers a centralized registry where features (and feature schemas) are stored for use within a team or wider organization. As a data scientist working on training your model, your requirements for how you access your batch / 'offline' data will almost certainly be different from how you access that data as part of a real-time or online inference setting. Feast solves the problem of developing [train-serve skew](https://ploomber.io/blog/train-serve-skew/) where those two sources of data diverge from each other. Feature stores are a relatively recent addition to commonly-used machine learning stacks. ### When to use it The feature store is an optional stack component in the ZenML Stack. The feature store as a technology should be used to store the features and inject them into the process on the server side. This includes * Productionalize new features * Reuse existing features across multiple pipelines and models * Achieve consistency between training and serving data (Training Serving Skew) * Provide a central registry of features and feature schemas ### List of available feature stores For production use cases, some more flavors can be found in specific `integrations` modules. In terms of features stores, ZenML features an integration of `feast`. | Feature Store | Flavor | Integration | Notes | |------------------------------------|----------|-------------|--------------------------------------------------------------------------| | [FeastFeatureStore](feast.md) | `feast` | `feast` | Connect ZenML with already existing Feast | | [Custom Implementation](custom.md) | _custom_ | | Extend the feature store abstraction and provide your own implementation | If you would like to see the available flavors for feature stores, you can use the command: ```shell zenml feature-store flavor list ``` ### How to use it The available implementation of the feature store is built on top of the feast integration, which means that using a feature store is no different from what's described on the [feast page: How to use it?](feast.md#how-do-you-use-it).
ZenML Scarf
================ File: docs/book/component-guide/image-builders/aws.md ================ --- description: Building container images with AWS CodeBuild --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # AWS Image Builder The AWS image builder is an [image builder](./image-builders.md) flavor provided by the ZenML `aws` integration that uses [AWS CodeBuild](https://aws.amazon.com/codebuild) to build container images. ### When to use it You should use the AWS image builder if: * you're **unable** to install or use [Docker](https://www.docker.com) on your client machine. * you're already using AWS. * your stack is mainly composed of other AWS components such as the [S3 Artifact Store](../artifact-stores/s3.md) or the [SageMaker Orchestrator](../orchestrators/sagemaker.md). ### How to deploy it {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including the AWS image builder? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), or [the ZenML AWS Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} ### How to use it To use the AWS image builder, you need: * The ZenML `aws` integration installed. If you haven't done so, run: ```shell zenml integration install aws ``` * An [S3 Artifact Store](../artifact-stores/s3.md) where the build context will be uploaded, so AWS CodeBuild can access it. * Recommended: an [AWS container registry](../container-registries/aws.md) where the built image will be pushed. The AWS CodeBuild service can also work with other container registries, but [explicit authentication](#authentication-methods) must be enabled in this case. * An [AWS CodeBuild project](https://aws.amazon.com/codebuild) created in the AWS account and region where you want to build the Docker images, preferably in the same region as the ECR container registry where images will be pushed (if applicable). The CodeBuild project configuration is largely irrelevant, as ZenML will override most of the default settings for each build according to the [AWS Docker build guide](https://docs.aws.amazon.com/codebuild/latest/userguide/sample-docker-section.html). Some example default configuration values are: * **Source Type**: `Amazon S3` * **Bucket**: The same S3 bucket used by the ZenML S3 Artifact Store. * **S3 folder**: any value (e.g. `codebuild`); * **Environment Type**: `Linux Container` * **Environment Image**: `bentolor/docker-dind-awscli` * **Privileged Mode**: `false` The user must take care that the **Service Role** attached to the CodeBuild project also has the necessary permissions to access the S3 bucket to read objects and the ECR container registry to push images (if applicable): ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:GetObjectVersion" ], "Resource": "arn:aws:s3:::/*" }, { "Effect": "Allow", "Action": [ "ecr:BatchGetImage", "ecr:DescribeImages", "ecr:BatchCheckLayerAvailability", "ecr:GetDownloadUrlForLayer", "ecr:InitiateLayerUpload", "ecr:UploadLayerPart", "ecr:CompleteLayerUpload", "ecr:PutImage" ], "Resource": "arn:aws:ecr:::repository/" }, { "Effect": "Allow", "Action": [ "ecr:GetAuthorizationToken" ], "Resource": "*" }, ] } ``` * Recommended: Grant ZenML access to trigger AWS CodeBuild builds by registering an [AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md) with the proper credentials and permissions, as covered in the [Authentication Methods](aws.md#authentication-methods) section. If not provided, the AWS credentials will be inferred from the environment where the pipeline is triggered. We can register the image builder and use it in our active stack: ```shell zenml image-builder register \ --flavor=aws \ --code_build_project= # Register and activate a stack with the new image builder zenml stack register -i ... --set ``` You also need to set up [authentication](aws.md#authentication-methods) required to access the CodeBuild AWS service. #### Authentication Methods Integrating and using an AWS Image Builder in your pipelines is not possible without employing some form of authentication. If you're looking for a quick way to get started locally, you can use the _Local Authentication_ method. However, the recommended way to authenticate to the AWS cloud platform is through [an AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md). This is particularly useful if you are configuring ZenML stacks that combine the AWS Image Builder with other remote stack components also running in AWS. {% tabs %} {% tab title="Implicit Authentication" %} This method uses the implicit AWS authentication available _in the environment where the ZenML code is running_. On your local machine, this is the quickest way to configure an AWS Image Builder. You don't need to supply credentials explicitly when you register the AWS Image Builder, as it leverages the local credentials and configuration that the AWS CLI stores on your local machine. However, you will need to install and set up the AWS CLI on your machine as a prerequisite, as covered in [the AWS CLI documentation](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html), before you register the AWS Image Builder. {% hint style="warning" %} Stacks using the AWS Image Builder set up with local authentication are not portable across environments. To make ZenML pipelines fully portable, it is recommended to use [an AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md) to authenticate your AWS Image Builder to the AWS cloud platform. {% endhint %} {% endtab %} {% tab title="AWS Service Connector (recommended)" %} To set up the AWS Image Builder to authenticate to AWS and access the AWS CodeBuild services, it is recommended to leverage the many features provided by [the AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md) such as auto-configuration, best security practices regarding long-lived credentials and reusing the same credentials across multiple stack components. If you don't already have an AWS Service Connector configured in your ZenML deployment, you can register one using the interactive CLI command. You also have the option to configure an AWS Service Connector that can be used to access more than just the AWS CodeBuild service: ```sh zenml service-connector register --type aws -i ``` A non-interactive CLI example that leverages [the AWS CLI configuration](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) on your local machine to auto-configure an AWS Service Connector for the AWS CodeBuild service: ```sh zenml service-connector register --type aws --resource-type aws-generic --auto-configure ``` {% code title="Example Command Output" %} ``` $ zenml service-connector register aws-generic --type aws --resource-type aws-generic --auto-configure Successfully registered service connector `aws-generic` with access to the following resources: ┏━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠────────────────┼────────────────┨ ┃ πŸ”Ά aws-generic β”‚ eu-central-1 ┃ ┗━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} > **Note**: Please remember to grant the entity associated with your AWS credentials permissions to access the CodeBuild API and to run CodeBuilder builds: > > ```json > { > "Version": "2012-10-17", > "Statement": [ > { > "Effect": "Allow", > "Action": [ > "codebuild:StartBuild", > "codebuild:BatchGetBuilds", > ], > "Resource": "arn:aws:codebuild:::project/" > }, > ] > } > ``` > The AWS Service Connector supports [many different authentication methods](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md#authentication-methods) with different levels of security and convenience. You should pick the one that best fits your use case. If you already have one or more AWS Service Connectors configured in your ZenML deployment, you can check which of them can be used to access generic AWS resources like the one required for your AWS Image Builder by running e.g.: ```sh zenml service-connector list-resources --resource-type aws-generic ``` {% code title="Example Command Output" %} ``` The following 'aws-generic' resources can be accessed by service connectors configured in your workspace: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────┼────────────────┨ ┃ 7113ba9b-efdd-4a0a-94dc-fb67926e58a1 β”‚ aws-generic β”‚ πŸ”Ά aws β”‚ πŸ”Ά aws-generic β”‚ eu-central-1 ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} After having set up or decided on an AWS Service Connector to use to authenticate to AWS, you can register the AWS Image Builder as follows: ```sh zenml image-builder register \ --flavor=aws \ --code_build_project= \ --connector ``` To connect an AWS Image Builder to an AWS Service Connector at a later point, you can use the following command: ```sh zenml image-builder connect --connector ``` {% code title="Example Command Output" %} ``` $ zenml image-builder connect aws-image-builder --connector aws-generic Successfully connected image builder `aws-image-builder` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────┼────────────────┨ ┃ 7113ba9b-efdd-4a0a-94dc-fb67926e58a1 β”‚ aws-generic β”‚ πŸ”Ά aws β”‚ πŸ”Ά aws-generic β”‚ eu-central-1 ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} As a final step, you can use the AWS Image Builder in a ZenML Stack: ```sh # Register and set a stack with the new image builder zenml stack register -i ... --set ``` {% endtab %} {% endtabs %} #### Customizing AWS CodeBuild builds The AWS Image Builder can be customized to a certain extent by providing additional configuration options when registering the image builder. The following additional attributes can be set: * `build_image`: The Docker image used to build the Docker image. The default is `bentolor/docker-dind-awscli`, which is a Docker image that includes both Docker-in-Docker and the AWS CLI. {% hint style="info" %} If you are running into Docker Hub rate-limits, it might be a good idea to copy this image to your own container registry and customize the `build_image` attribute to point to your own image. {% endhint %} * `compute_type`: The compute type used for the CodeBuild project. The default is `BUILD_GENERAL1_SMALL`. * `custom_env_vars`: A dictionary of custom environment variables to be set in the CodeBuild project. * `implicit_container_registry_auth`: A boolean flag that indicates whether to use implicit or explicit authentication when authenticating the AWS CodeBuild build to the target container registry: * when this is set to `true` (default), the builds will be configured to use whatever implicit authentication credentials are already available within the build container. As a special case for ECR registries, the service IAM role attached to the CodeBuild project is used to authenticate to the target ECR container registry and therefore the service role must include the necessary permissions to push images to the target ECR registry. * when set to `false`, the credentials attached to the ZenML Container Registry stack component in the active stack will be set as build environment variables and used to authenticate to the target container registry. This is useful when the target container registry is not an ECR registry or when the service role attached to the CodeBuild project does not have the necessary permissions to push images to the target ECR registry. This works best when the ZenML Container Registry stack component is also linked to the external container registry via a Service Connector.
ZenML Scarf
================ File: docs/book/component-guide/image-builders/custom.md ================ --- description: Learning how to develop a custom image builder. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a Custom Image Builder {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} ### Base Abstraction The `BaseImageBuilder` is the abstract base class that needs to be subclassed in order to create a custom component that can be used to build Docker images. As image builders can come in many shapes and forms, the base class exposes a deliberately basic and generic interface: ```python from abc import ABC, abstractmethod from typing import Any, Dict, Optional, Type, cast from zenml.container_registries import BaseContainerRegistry from zenml.enums import StackComponentType from zenml.image_builders import BuildContext from zenml.stack import Flavor, StackComponent from zenml.stack.stack_component import StackComponentConfig class BaseImageBuilder(StackComponent, ABC): """Base class for all ZenML image builders.""" @property def build_context_class(self) -> Type["BuildContext"]: """Build context class to use. The default build context class creates a build context that works for the Docker daemon. Override this method if your image builder requires a custom context. Returns: The build context class. """ return BuildContext @abstractmethod def build( self, image_name: str, build_context: "BuildContext", docker_build_options: Dict[str, Any], container_registry: Optional["BaseContainerRegistry"] = None, ) -> str: """Builds a Docker image. If a container registry is passed, the image will be pushed to that registry. Args: image_name: Name of the image to build. build_context: The build context to use for the image. docker_build_options: Docker build options. container_registry: Optional container registry to push to. Returns: The Docker image repo digest or name. """ ``` {% hint style="info" %} This is a slimmed-down version of the base implementation which aims to highlight the abstraction layer. In order to see the full implementation and get the complete docstrings, please check [the source code on GitHub](https://github.com/zenml-io/zenml/blob/main/src/zenml/image\_builders/base\_image\_builder.py) . {% endhint %} ### Build your own custom image builder If you want to create your own custom flavor for an image builder, you can follow the following steps: 1. Create a class that inherits from the `BaseImageBuilder` class and implement the abstract `build` method. This method should use the given build context and build a Docker image with it. If additionally a container registry is passed to the `build` method, the image builder is also responsible for pushing the image there. 2. If you need to provide any configuration, create a class that inherits from the `BaseImageBuilderConfig` class and adds your configuration parameters. 3. Bring both the implementation and the configuration together by inheriting from the `BaseImageBuilderFlavor` class. Make sure that you give a `name` to the flavor through its abstract property. Once you are done with the implementation, you can register it through the CLI. Please ensure you **point to the flavor class via dot notation**: ```shell zenml image-builder flavor register ``` For example, if your flavor class `MyImageBuilderFlavor` is defined in `flavors/my_flavor.py`, you'd register it by doing: ```shell zenml image-builder flavor register flavors.my_flavor.MyImageBuilderFlavor ``` {% hint style="warning" %} ZenML resolves the flavor class by taking the path where you initialized zenml (via `zenml init`) as the starting point of resolution. Therefore, please ensure you follow [the best practice](../../how-to/infrastructure-deployment/infrastructure-as-code/best-practices.md) of initializing zenml at the root of your repository. If ZenML does not find an initialized ZenML repository in any parent directory, it will default to the current working directory, but usually it's better to not have to rely on this mechanism, and initialize zenml at the root. {% endhint %} Afterward, you should see the new flavor in the list of available flavors: ```shell zenml image-builder flavor list ``` {% hint style="warning" %} It is important to draw attention to when and how these base abstractions are coming into play in a ZenML workflow. * The **CustomImageBuilderFlavor** class is imported and utilized upon the creation of the custom flavor through the CLI. * The **CustomImageBuilderConfig** class is imported when someone tries to register/update a stack component with this custom flavor. Especially, during the registration process of the stack component, the config will be used to validate the values given by the user. As `Config` objects are inherently `pydantic` objects, you can also add your own custom validators here. * The **CustomImageBuilder** only comes into play when the component is ultimately in use. The design behind this interaction lets us separate the configuration of the flavor from its implementation. This way we can register flavors and components even when the major dependencies behind their implementation are not installed in our local setting (assuming the `CustomImageBuilderFlavor` and the `CustomImageBuilderConfig` are implemented in a different module/path than the actual `CustomImageBuilder`). {% endhint %} #### Using a custom-build context The `BaseImageBuilder` abstraction uses the `build_context_class` to provide a class that should be used as the build context. In case your custom image builder requires a different build context than the default Docker build context, you can subclass the `BuildContext` class to customize the structure of your build context. In your image builder implementation, you can then overwrite the `build_context_class` property to specify your build context subclass.
ZenML Scarf
================ File: docs/book/component-guide/image-builders/gcp.md ================ --- description: Building container images with Google Cloud Build --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Google Cloud Image Builder The Google Cloud image builder is an [image builder](./image-builders.md) flavor provided by the ZenML `gcp` integration that uses [Google Cloud Build](https://cloud.google.com/build) to build container images. ### When to use it You should use the Google Cloud image builder if: * you're **unable** to install or use [Docker](https://www.docker.com) on your client machine. * you're already using GCP. * your stack is mainly composed of other Google Cloud components such as the [GCS Artifact Store](../artifact-stores/gcp.md) or the [Vertex Orchestrator](../orchestrators/vertex.md). ### How to deploy it {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including the Google Cloud image builder? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), the [stack registration wizard](../../how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md), or [the ZenML GCP Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} In order to use the ZenML Google Cloud image builder you need to enable Google Cloud Build relevant APIs on the Google Cloud project. ### How to use it To use the Google Cloud image builder, we need: * The ZenML `gcp` integration installed. If you haven't done so, run: ```shell zenml integration install gcp ``` * A [GCP Artifact Store](../artifact-stores/gcp.md) where the build context will be uploaded, so Google Cloud Build can access it. * A [GCP container registry](../container-registries/gcp.md) where the built image will be pushed. * Optionally, the GCP project ID in which you want to run the build and a service account with the needed permissions to run the build. If not provided, then the project ID and credentials will be inferred from the environment. * Optionally, you can change: * the Docker image used by Google Cloud Build to execute the steps to build and push the Docker image. By default, the builder image will be `'gcr.io/cloud-builders/docker'`. * The network to which the container used to build the ZenML pipeline Docker image will be attached. More information: [Cloud build network](https://cloud.google.com/build/docs/build-config-file-schema#network). * The build timeout for the build, and for the blocking operation waiting for the build to finish. More information: [Build Timeout](https://cloud.google.com/build/docs/build-config-file-schema#timeout\_2). We can register the image builder and use it in our active stack: ```shell zenml image-builder register \ --flavor=gcp \ --cloud_builder_image= \ --network= \ --build_timeout= # Register and activate a stack with the new image builder zenml stack register -i ... --set ``` You also need to set up [authentication](gcp.md#authentication-methods) required to access the Cloud Build GCP services. #### Authentication Methods Integrating and using a GCP Image Builder in your pipelines is not possible without employing some form of authentication. If you're looking for a quick way to get started locally, you can use the _Local Authentication_ method. However, the recommended way to authenticate to the GCP cloud platform is through [a GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md). This is particularly useful if you are configuring ZenML stacks that combine the GCP Image Builder with other remote stack components also running in GCP. {% tabs %} {% tab title="Implicit Authentication" %} This method uses the implicit GCP authentication available _in the environment where the ZenML code is running_. On your local machine, this is the quickest way to configure a GCP Image Builder. You don't need to supply credentials explicitly when you register the GCP Image Builder, as it leverages the local credentials and configuration that the Google Cloud CLI stores on your local machine. However, you will need to install and set up the Google Cloud CLI on your machine as a prerequisite, as covered in [the Google Cloud documentation](https://cloud.google.com/sdk/docs/install-sdk) , before you register the GCP Image Builder. {% hint style="warning" %} Stacks using the GCP Image Builder set up with local authentication are not portable across environments. To make ZenML pipelines fully portable, it is recommended to use [a GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) to authenticate your GCP Image Builder to the GCP cloud platform. {% endhint %} {% endtab %} {% tab title="GCP Service Connector (recommended)" %} To set up the GCP Image Builder to authenticate to GCP and access the GCP Cloud Build services, it is recommended to leverage the many features provided by [the GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) such as auto-configuration, best security practices regarding long-lived credentials and reusing the same credentials across multiple stack components. If you don't already have a GCP Service Connector configured in your ZenML deployment, you can register one using the interactive CLI command. You also have the option to configure a GCP Service Connector that can be used to access more than just the GCP Cloud Build service: ```sh zenml service-connector register --type gcp -i ``` A non-interactive CLI example that leverages [the Google Cloud CLI configuration](https://cloud.google.com/sdk/docs/install-sdk) on your local machine to auto-configure a GCP Service Connector for the GCP Cloud Build service: ```sh zenml service-connector register --type gcp --resource-type gcp-generic --resource-name --auto-configure ``` {% code title="Example Command Output" %} ``` $ zenml service-connector register gcp-generic --type gcp --resource-type gcp-generic --auto-configure Successfully registered service connector `gcp-generic` with access to the following resources: ┏━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠────────────────┼────────────────┨ ┃ πŸ”΅ gcp-generic β”‚ zenml-core ┃ ┗━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} > **Note**: Please remember to grant the entity associated with your GCP credentials permissions to access the Cloud Build API and to run Cloud Builder jobs (e.g. the [Cloud Build Editor IAM role](https://cloud.google.com/build/docs/iam-roles-permissions#predefined\_roles)). The GCP Service Connector supports [many different authentication methods](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md#authentication-methods) with different levels of security and convenience. You should pick the one that best fits your use case. If you already have one or more GCP Service Connectors configured in your ZenML deployment, you can check which of them can be used to access generic GCP resources like the GCP Image Builder required for your GCP Image Builder by running e.g.: ```sh zenml service-connector list-resources --resource-type gcp-generic ``` {% code title="Example Command Output" %} ``` The following 'gcp-generic' resources can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────┼────────────────┨ ┃ bfdb657d-d808-47e7-9974-9ba6e4919d83 β”‚ gcp-generic β”‚ πŸ”΅ gcp β”‚ πŸ”΅ gcp-generic β”‚ zenml-core ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} After having set up or decided on a GCP Service Connector to use to authenticate to GCP, you can register the GCP Image Builder as follows: ```sh zenml image-builder register \ --flavor=gcp \ --cloud_builder_image= \ --network= \ --build_timeout= # Connect the GCP Image Builder to GCP via a GCP Service Connector zenml image-builder connect -i ``` A non-interactive version that connects the GCP Image Builder to a target GCP Service Connector: ```sh zenml image-builder connect --connector ``` {% code title="Example Command Output" %} ``` $ zenml image-builder connect gcp-image-builder --connector gcp-generic Successfully connected image builder `gcp-image-builder` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────┼────────────────┨ ┃ bfdb657d-d808-47e7-9974-9ba6e4919d83 β”‚ gcp-generic β”‚ πŸ”΅ gcp β”‚ πŸ”΅ gcp-generic β”‚ zenml-core ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} As a final step, you can use the GCP Image Builder in a ZenML Stack: ```sh # Register and set a stack with the new image builder zenml stack register -i ... --set ``` {% endtab %} {% tab title="GCP Credentials" %} When you register the GCP Image Builder, you can [generate a GCP Service Account Key](https://cloud.google.com/docs/authentication/application-default-credentials#attached-sa), save it to a local file and then reference it in the Image Builder configuration. This method has the advantage that you don't need to install and configure the GCP CLI on your host, but it's still not as secure as using a GCP Service Connector and the stack component configuration is not portable to other hosts. For this method, you need to [create a user-managed GCP service account](https://cloud.google.com/iam/docs/service-accounts-create), and grant it privileges to access the Cloud Build API and to run Cloud Builder jobs (e.g. the [Cloud Build Editor IAM role](https://cloud.google.com/build/docs/iam-roles-permissions#predefined\_roles). With the service account key downloaded to a local file, you can register the GCP Image Builder as follows: ```shell zenml image-builder register \ --flavor=gcp \ --project= \ --service_account_path= \ --cloud_builder_image= \ --network= \ --build_timeout= # Register and set a stack with the new image builder zenml stack register -i ... --set ``` {% endtab %} {% endtabs %} ### Caveats As described in this [Google Cloud Build documentation page](https://cloud.google.com/build/docs/build-config-file-schema#network), Google Cloud Build uses containers to execute the build steps which are automatically attached to a network called `cloudbuild` that provides some Application Default Credentials (ADC), that allow the container to be authenticated and therefore use other GCP services. By default, the GCP Image Builder is executing the build command of the ZenML Pipeline Docker image with the option `--network=cloudbuild`, so the ADC provided by the `cloudbuild` network can also be used in the build. This is useful if you want to install a private dependency from a GCP Artifact Registry, but you will also need to use a [custom base parent image](../../how-to/customize-docker-builds/docker-settings-on-a-pipeline.md) with the [`keyrings.google-artifactregistry-auth`](https://pypi.org/project/keyrings.google-artifactregistry-auth/) installed, so `pip` can connect and authenticate in the private artifact registry to download the dependency. ```dockerfile FROM zenmldocker/zenml:latest RUN pip install keyrings.google-artifactregistry-auth ``` {% hint style="warning" %} The above `Dockerfile` uses `zenmldocker/zenml:latest` as a base image, but is recommended to change the tag to specify the ZenML version and Python version like `0.33.0-py3.10`. {% endhint %}
ZenML Scarf
================ File: docs/book/component-guide/image-builders/image-builders.md ================ --- icon: box-open description: Building container images for your ML workflow. --- # Image Builders The image builder is an essential part of most remote MLOps stacks. It is used to build container images such that your machine-learning pipelines and steps can be executed in remote environments. ### When to use it The image builder is needed whenever other components of your stack need to build container images. Currently, this is the case for most of ZenML's remote [orchestrators](../orchestrators/orchestrators.md) , [step operators](../step-operators/step-operators.md), and some [model deployers](../model-deployers/model-deployers.md). These containerize your pipeline code and therefore require an image builder to build [Docker](https://www.docker.com/) images. ### Image Builder Flavors Out of the box, ZenML comes with a `local` image builder that builds Docker images on your client machine. Additional image builders are provided by integrations: | Image Builder | Flavor | Integration | Notes | |------------------------------------|----------|-------------|--------------------------------------------------------------------------| | [LocalImageBuilder](local.md) | `local` | _built-in_ | Builds your Docker images locally. | | [KanikoImageBuilder](kaniko.md) | `kaniko` | `kaniko` | Builds your Docker images in Kubernetes using Kaniko. | | [GCPImageBuilder](gcp.md) | `gcp` | `gcp` | Builds your Docker images using Google Cloud Build. | | [AWSImageBuilder](aws.md) | `aws` | `aws` | Builds your Docker images using AWS Code Build. | | [Custom Implementation](custom.md) | _custom_ | | Extend the image builder abstraction and provide your own implementation | If you would like to see the available flavors of image builders, you can use the command: ```shell zenml image-builder flavor list ``` ### How to use it You don't need to directly interact with any image builder in your code. As long as the image builder that you want to use is part of your active [ZenML stack](../../user-guide/production-guide/understand-stacks.md), it will be used automatically by any component that needs to build container images.
ZenML Scarf
================ File: docs/book/component-guide/image-builders/kaniko.md ================ --- description: Building container images with Kaniko. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Kaniko Image Builder The Kaniko image builder is an [image builder](./image-builders.md) flavor provided by the ZenML `kaniko` integration that uses [Kaniko](https://github.com/GoogleContainerTools/kaniko) to build container images. ### When to use it You should use the Kaniko image builder if: * you're **unable** to install or use [Docker](https://www.docker.com) on your client machine. * you're familiar with/already using Kubernetes. ### How to deploy it In order to use the Kaniko image builder, you need a deployed Kubernetes cluster. ### How to use it To use the Kaniko image builder, we need: * The ZenML `kaniko` integration installed. If you haven't done so, run ```shell zenml integration install kaniko ``` * [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) installed. * A [remote container registry](../container-registries/container-registries.md) as part of your stack. * By default, the Kaniko image builder transfers the build context using the Kubernetes API. If you instead want to transfer the build context by storing it in the artifact store, you need to register it with the `store_context_in_artifact_store` attribute set to `True`. In this case, you also need a [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. * Optionally, you can change the timeout (in seconds) until the Kaniko pod is running in the orchestrator using the `pod_running_timeout` attribute. We can then register the image builder and use it in our active stack: ```shell zenml image-builder register \ --flavor=kaniko \ --kubernetes_context= [ --pod_running_timeout= ] # Register and activate a stack with the new image builder zenml stack register -i ... --set ``` For more information and a full list of configurable attributes of the Kaniko image builder, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-kaniko/#zenml.integrations.kaniko.image\_builders.kaniko\_image\_builder.KanikoImageBuilder) . #### Authentication for the container registry and artifact store The Kaniko image builder will create a Kubernetes pod that is running the build. This build pod needs to be able to pull from/push to certain container registries, and depending on the stack component configuration also needs to be able to read from the artifact store: * The pod needs to be authenticated to push to the container registry in your active stack. * In case the [parent image](../../how-to/customize-docker-builds/docker-settings-on-a-pipeline.md#using-a-custom-parent-image) you use in your `DockerSettings` is stored in a private registry, the pod needs to be authenticated to pull from this registry. * If you configured your image builder to store the build context in the artifact store, the pod needs to be authenticated to read files from the artifact store storage. ZenML is not yet able to handle setting all of the credentials of the various combinations of container registries and artifact stores on the Kaniko build pod, which is you're required to set this up yourself for now. The following section outlines how to handle it in the most straightforward (and probably also most common) scenario, when the Kubernetes cluster you're using for the Kaniko build is hosted on the same cloud provider as your container registry (and potentially the artifact store). For all other cases, check out the [official Kaniko repository](https://github.com/GoogleContainerTools/kaniko) for more information. {% tabs %} {% tab title="AWS" %} * Add permissions to push to ECR by attaching the `EC2InstanceProfileForImageBuilderECRContainerBuilds` policy to your [EKS node IAM role](https://docs.aws.amazon.com/eks/latest/userguide/create-node-role.html). * Configure the image builder to set some required environment variables on the Kaniko build pod: ```shell # register a new image builder with the environment variables zenml image-builder register \ --flavor=kaniko \ --kubernetes_context= \ --env='[{"name": "AWS_SDK_LOAD_CONFIG", "value": "true"}, {"name": "AWS_EC2_METADATA_DISABLED", "value": "true"}]' # or update an existing one zenml image-builder update \ --env='[{"name": "AWS_SDK_LOAD_CONFIG", "value": "true"}, {"name": "AWS_EC2_METADATA_DISABLED", "value": "true"}]' ``` Check out [the Kaniko docs](https://github.com/GoogleContainerTools/kaniko#pushing-to-amazon-ecr) for more information. {% endtab %} {% tab title="GCP" %} * [Enable workload identity](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity#enable\_on\_cluster) for your cluster * Follow the steps described [here](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity#authenticating\_to) to create a Google service account, a Kubernetes service account as well as an IAM policy binding between them. * Grant the Google service account permissions to push to your GCR registry and read from your GCP bucket. * Configure the image builder to run in the correct namespace and use the correct service account: ```shell # register a new image builder with namespace and service account zenml image-builder register \ --flavor=kaniko \ --kubernetes_context= \ --kubernetes_namespace= \ --service_account_name= # --executor_args='["--compressed-caching=false", "--use-new-run=true"]' # or update an existing one zenml image-builder update \ --kubernetes_namespace= \ --service_account_name= ``` Check out [the Kaniko docs](https://github.com/GoogleContainerTools/kaniko#pushing-to-google-gcr) for more information. {% endtab %} {% tab title="Azure" %} * Create a Kubernetes `configmap` for a Docker config that uses the Azure credentials helper: ```shell kubectl create configmap docker-config --from-literal='config.json={ "credHelpers": { "mycr.azurecr.io": "acr-env" } }' ``` * Follow [these steps](https://learn.microsoft.com/en-us/azure/aks/use-managed-identity) to configure your cluster to use a managed identity * Configure the image builder to mount the `configmap` in the Kaniko build pod: ```shell # register a new image builder with the mounted configmap zenml image-builder register \ --flavor=kaniko \ --kubernetes_context= \ --volume_mounts='[{"name": "docker-config", "mountPath": "/kaniko/.docker/"}]' \ --volumes='[{"name": "docker-config", "configMap": {"name": "docker-config"}}]' # --executor_args='["--compressed-caching=false", "--use-new-run=true"]' # or update an existing one zenml image-builder update \ --volume_mounts='[{"name": "docker-config", "mountPath": "/kaniko/.docker/"}]' \ --volumes='[{"name": "docker-config", "configMap": {"name": "docker-config"}}]' ``` Check out [the Kaniko docs](https://github.com/GoogleContainerTools/kaniko#pushing-to-azure-container-registry) for more information. {% endtab %} {% endtabs %} #### Passing additional parameters to the Kaniko build You can pass additional parameters to the Kaniko build by setting the `executor_args` attribute of the image builder. ```shell zenml image-builder register \ --flavor=kaniko \ --kubernetes_context= \ --executor_args='["--label", "key=value"]' # Adds a label to the final image ``` List of some possible additional flags: * `--cache`: Set to `false` to disable caching. Defaults to `true`. * `--cache-dir`: Set the directory where to store cached layers. Defaults to `/cache`. * `--cache-repo`: Set the repository where to store cached layers. Defaults to `gcr.io/kaniko-project/executor`. * `--cache-ttl`: Set the cache expiration time. Defaults to `24h`. * `--cleanup`: Set to `false` to disable cleanup of the working directory. Defaults to `true`. * `--compressed-caching`: Set to `false` to disable compressed caching. Defaults to `true`. For a full list of possible flags, check out the [Kaniko additional flags](https://github.com/GoogleContainerTools/kaniko#additional-flags)
ZenML Scarf
================ File: docs/book/component-guide/image-builders/local.md ================ --- description: Building container images locally. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Local Image Builder The local image builder is an [image builder](./image-builders.md) flavor that comes built-in with ZenML and uses the local Docker installation on your client machine to build container images. {% hint style="info" %} ZenML uses the official Docker Python library to build and push your images. This library loads its authentication credentials to push images from the default config location: `$HOME/.docker/config.json`. If your Docker configuration is stored in a different directory, you can use the environment variable `DOCKER_CONFIG` to override this behavior: ```shell export DOCKER_CONFIG=/path/to/config_dir ``` The directory that you specify here must contain your Docker configuration in a file called `config.json`. {% endhint %} ### When to use it You should use the local image builder if: * you're able to install and use [Docker](https://www.docker.com) on your client machine. * you want to use remote components that require containerization without the additional hassle of configuring infrastructure for an additional component. ### How to deploy it The local image builder comes with ZenML and works without any additional setup. ### How to use it To use the Local image builder, we need: * [Docker](https://www.docker.com) installed and running. * The Docker client authenticated to push to the container registry that you intend to use in the same stack. We can then register the image builder and use it to create a new stack: ```shell zenml image-builder register --flavor=local # Register and activate a stack with the new image builder zenml stack register -i ... --set ``` For more information and a full list of configurable attributes of the local image builder, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-image\_builders/#zenml.image\_builders.local\_image\_builder.LocalImageBuilder) .
ZenML Scarf
================ File: docs/book/component-guide/model-deployers/bentoml.md ================ --- description: Deploying your models locally with BentoML. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # BentoML BentoML is an open-source framework for machine learning model serving. it can be used to deploy models locally, in a cloud environment, or in a Kubernetes environment. The BentoML Model Deployer is one of the available flavors of the [Model Deployer](./model-deployers.md) stack component. Provided with the BentoML integration it can be used to deploy and [manage BentoML models](https://docs.bentoml.org/en/latest/guides/model-store.html#manage-models) or [Bento](https://docs.bentoml.org/en/latest/reference/stores.html#manage-bentos) on a local running HTTP server. {% hint style="warning" %} The BentoML Model Deployer can be used to deploy models for local development and production use cases. There are two paths to deploy Bentos with ZenML, one as a local http server and one as a containerized service. Within the BentoML ecosystem, [Yatai](https://github.com/bentoml/Yatai) and [`bentoctl`](https://github.com/bentoml/bentoctl) are the tools responsible for deploying the Bentos into the Kubernetes cluster and Cloud Platforms. `bentoctl` is deprecated now and might not work with the latest BentoML versions. {% endhint %} ## When to use it? You should use the BentoML Model Deployer to: * Standardize the way you deploy your models to production within your organization. * if you are looking to deploy your models in a simple way, while you are still able to transform your model into a production-ready solution when that time comes. If you are looking to deploy your models with other Kubernetes-based solutions, you can take a look at one of the other [Model Deployer Flavors](./model-deployers.md#model-deployers-flavors) available in ZenML. BentoML also allows you to deploy your models in a more complex production-grade setting. [Bentoctl](https://github.com/bentoml/bentoctl) is one of the tools that can help you get there. Bentoctl takes your built Bento from a ZenML pipeline and deploys it with `bentoctl` into a cloud environment such as AWS Lambda, AWS SageMaker, Google Cloud Functions, Google Cloud AI Platform, or Azure Functions. Read more about this in the [From Local to Cloud with `bentoctl` section](#from-local-to-cloud-with-bentoctl). {% hint style="info" %} The `bentoctl` integration implementation is still in progress and will be available soon. The integration will allow you to deploy your models to a specific cloud provider with just a few lines of code using ZenML built-in steps. {% endhint %} ## How do you deploy it? Within ZenML you can quickly get started with BentoML by simply creating Model Deployer Stack Component with the BentoML flavor. To do so you'll need to install the required Python packages on your local machine to be able to deploy your models: ```bash zenml integration install bentoml -y ``` To register the BentoML model deployer with ZenML you need to run the following command: ```bash zenml model-deployer register bentoml_deployer --flavor=bentoml ``` The ZenML integration will provision a local HTTP deployment server as a daemon process that will continue to run in the background to serve the latest models and Bentos. ## How do you use it? The recommended flow to use the BentoML model deployer is to first [create a BentoML Service](#create-a-bentoml-service), then either build a [bento yourself](#build-your-own-bento) or [use the `bento_builder_step`](#zenml-bento-builder-step) to build the model and service into a bento bundle, and finally [deploy the bundle with the `bentoml_model_deployer_step`](#zenml-bentoml-deployer-step). ### Create a BentoML Service The first step to being able to deploy your models and use BentoML is to create a [bento service](https://docs.bentoml.com/en/latest/guides/services.html) which is the main logic that defines how your model will be served. The The following example shows how to create a basic bento service that will be used to serve a torch model. Learn more about how to specify the inputs and outputs for the APIs and how to use validators in the [Input and output types BentoML docs](https://docs.bentoml.com/en/latest/guides/iotypes.html) ```python import bentoml from bentoml.validators import DType, Shape import numpy as np import torch @bentoml.service( name=SERVICE_NAME, ) class MNISTService: def __init__(self): # load model self.model = bentoml.pytorch.load_model(MODEL_NAME) self.model.eval() @bentoml.api() async def predict_ndarray( self, inp: Annotated[np.ndarray, DType("float32"), Shape((28, 28))] ) -> np.ndarray: inp = np.expand_dims(inp, (0, 1)) output_tensor = await self.model(torch.tensor(inp)) return to_numpy(output_tensor) @bentoml.api() async def predict_image(self, f: PILImage) -> np.ndarray: assert isinstance(f, PILImage) arr = np.array(f) / 255.0 assert arr.shape == (28, 28) arr = np.expand_dims(arr, (0, 1)).astype("float32") output_tensor = await self.model(torch.tensor(arr)) return to_numpy(output_tensor) ``` ### πŸ—οΈ Build your own bento The `bento_builder_step` only exists to make your life easier; you can always build the bento yourself and use it in the deployer step in the next section. A peek into how this step is implemented will give you ideas on how to build such a function yourself. This allows you to have more customization over the bento build process if needed. ```python # 1. use the step context to get the output artifact uri context = get_step_context() # 2. you can save the model and bento uri as part of the bento labels labels = labels or {} labels["model_uri"] = model.uri labels["bento_uri"] = os.path.join( context.get_output_artifact_uri(), DEFAULT_BENTO_FILENAME ) # 3. Load the model from the model artifact model = load_artifact_from_response(model) # 4. Save the model to a BentoML model based on the model type try: module = importlib.import_module(f".{model_type}", "bentoml") module.save_model(model_name, model, labels=labels) except importlib.metadata.PackageNotFoundError: bentoml.picklable_model.save_model( model_name, model, ) # 5. Build the BentoML bundle. You can use any of the parameters supported by the bentos.build function. bento = bentos.build( service=service, models=[model_name], version=version, labels=labels, description=description, include=include, exclude=exclude, python=python, docker=docker, build_ctx=working_dir or source_utils.get_source_root(), ) ``` The `model_name` here should be the name with which your model is saved to BentoML, typically through one of the following commands. More information about the BentoML model store and how to save models there can be found here on the [BentoML docs](https://docs.bentoml.org/en/latest/guides/model-store.html#save-a-model). ```python bentoml.MODEL_TYPE.save_model(model_name, model, labels=labels) # or bentoml.picklable_model.save_model( model_name, model, ) ``` Now, your custom step could look something like this: ```python from zenml import step @step def my_bento_builder(model) -> bento.Bento: ... # Load the model from the model artifact model = load_artifact_from_response(model) # save to bentoml bentoml.pytorch.save_model(model_name, model) # Build the BentoML bundle. You can use any of the parameters supported by the bentos.build function. bento = bentos.build( ... ) return bento ``` You can now use this bento in any way you see fit. ### ZenML Bento Builder step Once you have your bento service defined, we can use the built-in bento builder step to build the bento bundle that will be used to serve the model. The following example shows how can call the built-in bento builder step within a ZenML pipeline. Make sure you have the bento service file in your repository and at the root-level and then use the correct class name in the `service` parameter. ```python from zenml import pipeline, step from zenml.integrations.bentoml.steps import bento_builder_step @pipeline def bento_builder_pipeline(): model = ... bento = bento_builder_step( model=model, model_name="pytorch_mnist", # Name of the model model_type="pytorch", # Type of the model (pytorch, tensorflow, sklearn, xgboost..) service="service.py:CLASS_NAME", # Path to the service file within zenml repo labels={ # Labels to be added to the bento bundle "framework": "pytorch", "dataset": "mnist", "zenml_version": "0.21.1", }, exclude=["data"], # Exclude files from the bento bundle python={ "packages": ["zenml", "torch", "torchvision"], }, # Python package requirements of the model ) ``` The Bento Builder step can be used in any orchestration pipeline that you create with ZenML. The step will build the bento bundle and save it to the used artifact store. Which can be used to serve the model in a local or containerized setting using the BentoML Model Deployer Step, or in a remote setting using the `bentoctl` or Yatai. This gives you the flexibility to package your model in a way that is ready for different deployment scenarios. ### ZenML BentoML Deployer step We have now built our bento bundle, and we can use the built-in `bentoml_model_deployer_step` to deploy the bento bundle to our local HTTP server or to a containerized service running in your local machine. {% hint style="info" %} The `bentoml_model_deployer_step` can only be used in a local environment. But in the case of using containerized deployment, you can use the Docker image created by the `bentoml_model_deployer_step` to deploy your model to a remote environment. It is automatically pushed to your ZenML Stack's container registry. {% endhint %} **Local deployment** The following example shows how to use the `bentoml_model_deployer_step` to deploy the bento bundle to a local HTTP server. ```python from zenml import pipeline, step from zenml.integrations.bentoml.steps import bentoml_model_deployer_step @pipeline def bento_deployer_pipeline(): bento = ... deployed_model = bentoml_model_deployer_step( bento=bento model_name="pytorch_mnist", # Name of the model port=3001, # Port to be used by the http server ) ``` **Containerized deployment** The following example shows how to use the `bentoml_model_deployer_step` to deploy the bento bundle to a [containerized service](https://docs.bentoml.org/en/latest/guides/containerization.html) running in your local machine. Make sure you have the `docker` CLI installed on your local machine to be able to build an image and deploy the containerized service. You can choose to give a name and a tag to the image that will be built and pushed to your ZenML Stack's container registry. By default, the bento tag is used. If you are providing a custom image name, make sure that you attach the right registry name as prefix to the image name, otherwise the image push will fail. ```python from zenml import pipeline, step from zenml.integrations.bentoml.steps import bentoml_model_deployer_step @pipeline def bento_deployer_pipeline(): bento = ... deployed_model = bentoml_model_deployer_step( bento=bento model_name="pytorch_mnist", # Name of the model port=3001, # Port to be used by the http server deployment_type="container", image="my-custom-image", image_tag="my-custom-image-tag", platform="linux/amd64", ) ``` This step: - builds a docker image for the bento and pushes it to the container registry - runs the docker image locally to make it ready for inference You can find the image on your machine by running: ```bash docker images ``` and also the running container by running: ```bash docker ps ``` The image is also pushed to the container registry of your ZenML stack. You can run the image in any environment with a sample command like this: ```bash docker run -it --rm -p 3000:3000 image:image-tag serve ``` ### ZenML BentoML Pipeline examples Once all the steps have been defined, we can create a ZenML pipeline and run it. The bento builder step expects to get the trained model as an input, so we need to make sure either we have a previous step that trains the model and outputs it or loads the model from a previous run. Then the deployer step expects to get the bento bundle as an input, so we need to make sure either we have a previous step that builds the bento bundle and outputs it or load the bento bundle from a previous run or external source. The following example shows how to create a ZenML pipeline that trains a model, builds a bento bundle, creates and runs a docker image for it and pushes it to the container registry. You can then have a different pipeline that retrieves the image and deploys it to a remote environment. ```python # Import the pipeline to use the pipeline decorator from zenml.pipelines import pipeline # Pipeline definition @pipeline def bentoml_pipeline( importer, trainer, evaluator, deployment_trigger, bento_builder, deployer, ): """Link all the steps and artifacts together""" train_dataloader, test_dataloader = importer() model = trainer(train_dataloader) accuracy = evaluator(test_dataloader=test_dataloader, model=model) decision = deployment_trigger(accuracy=accuracy) bento = bento_builder(model=model) deployer(deploy_decision=decision, bento=bento, deployment_type="container") ``` In more complex scenarios, you might want to build a pipeline that trains a model and builds a bento bundle in a remote environment. Then creates a new pipeline that retrieves the bento bundle and deploys it to a local http server, or to a cloud provider. The following example shows a pipeline example that does exactly that. ```python # Import the pipeline to use the pipeline decorator from zenml.pipelines import pipeline # Pipeline definition @pipeline def remote_train_pipeline( importer, trainer, evaluator, bento_builder, ): """Link all the steps and artifacts together""" train_dataloader, test_dataloader = importer() model = trainer(train_dataloader) accuracy = evaluator(test_dataloader=test_dataloader, model=model) bento = bento_builder(model=model) @pipeline def local_deploy_pipeline( bento_loader, deployer, ): """Link all the steps and artifacts together""" bento = bento_loader() deployer(deploy_decision=decision, bento=bento) ``` ### Predicting with the local deployed model Once the model has been deployed we can use the BentoML client to send requests to the deployed model. ZenML will automatically create a BentoML client for you and you can use it to send requests to the deployed model by simply calling the service to predict the method and passing the input data and the API function name. The following example shows how to use the BentoML client to send requests to the deployed model. ```python @step def predictor( inference_data: Dict[str, List], service: BentoMLDeploymentService, ) -> None: """Run an inference request against the BentoML prediction service. Args: service: The BentoML service. data: The data to predict. """ service.start(timeout=10) # should be a NOP if already started for img, data in inference_data.items(): prediction = service.predict("predict_ndarray", np.array(data)) result = to_labels(prediction[0]) rich_print(f"Prediction for {img} is {result}") ``` Deploying and testing locally is a great way to get started and test your model. However, a real-world scenario will most likely require you to deploy your model to a remote environment. You can choose to deploy your model as a container image by setting the `deployment_type` to container in the deployer step and then use the image created in a remote environment. You can also use `bentoctl` or `yatai` to deploy the bento to a cloud environment. ### From Local to Cloud with `bentoctl` {% hint style="warning" %} The `bentoctl` CLI is now deprecated and might not work with the latest BentoML versions. {% endhint %} Bentoctl helps deploy any machine learning models as production-ready API endpoints into the cloud. It is a command line tool that provides a simple interface to manage your BentoML bundles. The `bentoctl` CLI provides a list of operators which are plugins that interact with cloud services, some of these operators are: * [AWS Lambda](https://github.com/bentoml/aws-lambda-deploy) * [AWS SageMaker](https://github.com/bentoml/aws-sagemaker-deploy) * [AWS EC2](https://github.com/bentoml/aws-ec2-deploy) * [Google Cloud Run](https://github.com/bentoml/google-cloud-run-deploy) * [Google Compute Engine](https://github.com/bentoml/google-compute-engine-deploy) * [Azure Container Instances](https://github.com/bentoml/azure-container-instances-deploy) * [Heroku](https://github.com/bentoml/heroku-deploy) You can find more information about the `bentoctl` tool [on the official GitHub repository](https://github.com/bentoml/bentoctl). For more information and a full list of configurable attributes of the BentoML Model Deployer, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-bentoml/#zenml.integrations.bentoml.model_deployers.bentoml_model_deployer) .
ZenML Scarf
================ File: docs/book/component-guide/model-deployers/custom.md ================ --- description: Learning how to develop a custom model deployer. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a Custom Model Deployer {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} To deploy and manage your trained machine-learning models, ZenML provides a stack component called `Model Deployer`. This component is responsible for interacting with the deployment tool, framework, or platform. When present in a stack, the model deployer can also act as a registry for models that are served with ZenML. You can use the model deployer to list all models that are currently deployed for online inference or filtered according to a particular pipeline run or step, or to suspend, resume or delete an external model server managed through ZenML. ### Base Abstraction In ZenML, the base abstraction of the model deployer is built on top of three major criteria: 1. It needs to ensure efficient deployment and management of models in accordance with the specific requirements of the serving infrastructure, by holding all the stack-related configuration attributes required to interact with the remote model serving tool, service, or platform. 2. It needs to implement the continuous deployment logic necessary to deploy models in a way that updates an existing model server that is already serving a previous version of the same model instead of creating a new model server for every new model version (see the `deploy_model` abstract method). This functionality can be consumed directly from ZenML pipeline steps, but it can also be used outside the pipeline to deploy ad-hoc models. It is also usually coupled with a standard model deployer step, implemented by each integration, that hides the details of the deployment process from the user. 3. It needs to act as a ZenML BaseService registry, where every BaseService instance is used as an internal representation of a remote model server (see the `find_model_server` abstract method). To achieve this, it must be able to re-create the configuration of a BaseService from information that is persisted externally, alongside, or even as part of the remote model server configuration itself. For example, for model servers that are implemented as Kubernetes resources, the BaseService instances can be serialized and saved as Kubernetes resource annotations. This allows the model deployer to keep track of all externally running model servers and to re-create their corresponding BaseService instance representations at any given time. The model deployer also defines methods that implement basic life-cycle management on remote model servers outside the coverage of a pipeline (see `stop_model_server` , `start_model_server` and `delete_model_server`). Putting all these considerations together, we end up with the following interface: ```python from abc import ABC, abstractmethod from typing import Dict, List, Optional, Type from uuid import UUID from zenml.enums import StackComponentType from zenml.services import BaseService, ServiceConfig from zenml.stack import StackComponent, StackComponentConfig, Flavor DEFAULT_DEPLOYMENT_START_STOP_TIMEOUT = 300 class BaseModelDeployerConfig(StackComponentConfig): """Base class for all ZenML model deployer configurations.""" class BaseModelDeployer(StackComponent, ABC): """Base class for all ZenML model deployers.""" @abstractmethod def perform_deploy_model( self, id: UUID, config: ServiceConfig, timeout: int = DEFAULT_DEPLOYMENT_START_STOP_TIMEOUT, ) -> BaseService: """Abstract method to deploy a model.""" @staticmethod @abstractmethod def get_model_server_info( service: BaseService, ) -> Dict[str, Optional[str]]: """Give implementation-specific way to extract relevant model server properties for the user.""" @abstractmethod def perform_stop_model( self, service: BaseService, timeout: int = DEFAULT_DEPLOYMENT_START_STOP_TIMEOUT, force: bool = False, ) -> BaseService: """Abstract method to stop a model server.""" @abstractmethod def perform_start_model( self, service: BaseService, timeout: int = DEFAULT_DEPLOYMENT_START_STOP_TIMEOUT, ) -> BaseService: """Abstract method to start a model server.""" @abstractmethod def perform_delete_model( self, service: BaseService, timeout: int = DEFAULT_DEPLOYMENT_START_STOP_TIMEOUT, force: bool = False, ) -> None: """Abstract method to delete a model server.""" class BaseModelDeployerFlavor(Flavor): """Base class for model deployer flavors.""" @property @abstractmethod def name(self): """Returns the name of the flavor.""" @property def type(self) -> StackComponentType: """Returns the flavor type. Returns: The flavor type. """ return StackComponentType.MODEL_DEPLOYER @property def config_class(self) -> Type[BaseModelDeployerConfig]: """Returns `BaseModelDeployerConfig` config class. Returns: The config class. """ return BaseModelDeployerConfig @property @abstractmethod def implementation_class(self) -> Type[BaseModelDeployer]: """The class that implements the model deployer.""" ``` {% hint style="info" %} This is a slimmed-down version of the base implementation which aims to highlight the abstraction layer. In order to see the full implementation and get the complete docstrings, please check the [SDK docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-model\_deployers/#zenml.model\_deployers.base\_model\_deployer.BaseModelDeployer) . {% endhint %} ### Building your own model deployers If you want to create your own custom flavor for a model deployer, you can follow the following steps: 1. Create a class that inherits from the `BaseModelDeployer` class and implements the abstract methods. 2. If you need to provide any configuration, create a class that inherits from the `BaseModelDeployerConfig` class and add your configuration parameters. 3. Bring both the implementation and the configuration together by inheriting from the `BaseModelDeployerFlavor` class. Make sure that you give a `name` to the flavor through its abstract property. 4. Create a service class that inherits from the `BaseService` class and implements the abstract methods. This class will be used to represent the deployed model server in ZenML. Once you are done with the implementation, you can register it through the CLI. Please ensure you **point to the flavor class via dot notation**: ```shell zenml model-deployer flavor register ``` For example, if your flavor class `MyModelDeployerFlavor` is defined in `flavors/my_flavor.py`, you'd register it by doing: ```shell zenml model-deployer flavor register flavors.my_flavor.MyModelDeployerFlavor ``` {% hint style="warning" %} ZenML resolves the flavor class by taking the path where you initialized zenml (via `zenml init`) as the starting point of resolution. Therefore, please ensure you follow [the best practice](../../how-to/infrastructure-deployment/infrastructure-as-code/best-practices.md) of initializing zenml at the root of your repository. If ZenML does not find an initialized ZenML repository in any parent directory, it will default to the current working directory, but usually, it's better to not have to rely on this mechanism and initialize zenml at the root. {% endhint %} Afterward, you should see the new flavor in the list of available flavors: ```shell zenml model-deployer flavor list ``` {% hint style="warning" %} It is important to draw attention to when and how these base abstractions are coming into play in a ZenML workflow. * The **CustomModelDeployerFlavor** class is imported and utilized upon the creation of the custom flavor through the CLI. * The **CustomModelDeployerConfig** class is imported when someone tries to register/update a stack component with this custom flavor. Especially, during the registration process of the stack component, the config will be used to validate the values given by the user. As `Config` objects are inherently `pydantic` objects, you can also add your own custom validators here. * The **CustomModelDeployer** only comes into play when the component is ultimately in use. The design behind this interaction lets us separate the configuration of the flavor from its implementation. This way we can register flavors and components even when the major dependencies behind their implementation are not installed in our local setting (assuming the `CustomModelDeployerFlavor` and the `CustomModelDeployerConfig` are implemented in a different module/path than the actual `CustomModelDeployer`). {% endhint %}
ZenML Scarf
================ File: docs/book/component-guide/model-deployers/databricks.md ================ --- description: >- Deploying models to Databricks Inference Endpoints with Databricks --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Databricks Databricks Model Serving or Mosaic AI Model Serving provides a unified interface to deploy, govern, and query AI models. Each model you serve is available as a REST API that you can integrate into your web or client application. This service provides dedicated and autoscaling infrastructure managed by Databricks, allowing you to deploy models without dealing with containers and GPUs. {% hint style="info" %} Databricks Model deployer can be considered as a managed service for deploying models using MLflow, This means you can switch between MLflow and Databricks Model Deployers without changing your pipeline code even for custom complex models. {% endhint %} ## When to use it? You should use Databricks Model Deployer: * You are already using Databricks for your data and ML workloads. * If you want to deploy AI models without dealing with containers and GPUs, Databricks Model Deployer provides a unified interface to deploy, govern, and query models. * Databricks Model Deployer offers dedicated and autoscaling infrastructure managed by Databricks, making it easier to deploy models at scale. * Enterprise security is a priority, and you need to deploy models into secure offline endpoints accessible only via a direct connection to your Virtual Private Cloud (VPCs). * if your goal is to turn your models into production-ready APIs with minimal infrastructure or MLOps involvement. If you are looking for a more easy way to deploy your models locally, you can use the [MLflow Model Deployer](mlflow.md) flavor. ## How to deploy it? The Databricks Model Deployer flavor is provided by the Databricks ZenML integration, so you need to install it on your local machine to be able to deploy your models. You can do this by running the following command: ```bash zenml integration install databricks -y ``` To register the Databricks model deployer with ZenML you need to run the following command: ```bash zenml model-deployer register --flavor=databricks --host= --client_id={{databricks.client_id}} --client_secret={{databricks.client_secret}} ``` {% hint style="info" %} We recommend creating a Databricks service account with the necessary permissions to create and run jobs. You can find more information on how to create a service account [here](https://docs.databricks.com/dev-tools/api/latest/authentication.html). You can generate a client_id and client_secret for the service account and use them to authenticate with Databricks. {% endhint %} We can now use the model deployer in our stack. ```bash zenml stack update --model-deployer= ``` See the [databricks\_model\_deployer\_step](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-databricks/#zenml.integrations.databricks.steps.databricks\_deployer.databricks\_model\_deployer\_step) for an example of using the Databricks Model Deployer to deploy a model inside a ZenML pipeline step. ## Configuration Within the `DatabricksServiceConfig` you can configure: * `model_name`: The name of the model that will be served, this will be used to identify the model in the Databricks Model Registry. * `model_version`: The version of the model that will be served, this will be used to identify the model in the Databricks Model Registry. * `workload_size`: The size of the workload that the model will be serving. This can be `Small`, `Medium`, or `Large`. * `scale_to_zero_enabled`: A boolean flag to enable or disable the scale to zero feature. * `env_vars`: A dictionary of environment variables to be passed to the model serving container. * `workload_type`: The type of workload that the model will be serving. This can be `CPU`, `GPU_LARGE`, `GPU_MEDIUM`, `GPU_SMALL`, or `MULTIGPU_MEDIUM`. * `endpoint_secret_name`: The name of the secret that will be used to secure the endpoint and authenticate requests. For more information and a full list of configurable attributes of the Databricks Model Deployer, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-databricks/#zenml.integrations.databricks.model\_deployers) and Databricks endpoint [code](https://github.com/databricks/databricks\_hub/blob/5e3b603ccc7cd6523d998e75f82848215abf9415/src/databricks\_hub/hf\_api.py#L6957). ### Run inference on a provisioned inference endpoint The following code example shows how to run inference against a provisioned inference endpoint: ```python from typing import Annotated from zenml import step, pipeline from zenml.integrations.databricks.model_deployers import DatabricksModelDeployer from zenml.integrations.databricks.services import DatabricksDeploymentService # Load a prediction service deployed in another pipeline @step(enable_cache=False) def prediction_service_loader( pipeline_name: str, pipeline_step_name: str, running: bool = True, model_name: str = "default", ) -> DatabricksDeploymentService: """Get the prediction service started by the deployment pipeline. Args: pipeline_name: name of the pipeline that deployed the MLflow prediction server step_name: the name of the step that deployed the MLflow prediction server running: when this flag is set, the step only returns a running service model_name: the name of the model that is deployed """ # get the Databricks model deployer stack component model_deployer = DatabricksModelDeployer.get_active_model_deployer() # fetch existing services with same pipeline name, step name and model name existing_services = model_deployer.find_model_server( pipeline_name=pipeline_name, pipeline_step_name=pipeline_step_name, model_name=model_name, running=running, ) if not existing_services: raise RuntimeError( f"No Databricks inference endpoint deployed by step " f"'{pipeline_step_name}' in pipeline '{pipeline_name}' with name " f"'{model_name}' is currently running." ) return existing_services[0] # Use the service for inference @step def predictor( service: DatabricksDeploymentService, data: str ) -> Annotated[str, "predictions"]: """Run a inference request against a prediction service""" prediction = service.predict(data) return prediction @pipeline def databricks_deployment_inference_pipeline( pipeline_name: str, pipeline_step_name: str = "databricks_model_deployer_step", ): inference_data = ... model_deployment_service = prediction_service_loader( pipeline_name=pipeline_name, pipeline_step_name=pipeline_step_name, ) predictions = predictor(model_deployment_service, inference_data) ``` For more information and a full list of configurable attributes of the Databricks Model Deployer, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-databricks/#zenml.integrations.databricks.model\_deployers).
ZenML Scarf
================ File: docs/book/component-guide/model-deployers/huggingface.md ================ --- description: >- Deploying models to Huggingface Inference Endpoints with Hugging Face :hugging_face:. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Hugging Face Hugging Face Inference Endpoints provides a secure production solution to easily deploy any `transformers`, `sentence-transformers`, and `diffusers` models on a dedicated and autoscaling infrastructure managed by Hugging Face. An Inference Endpoint is built from a model from the [Hub](https://huggingface.co/models). This service provides dedicated and autoscaling infrastructure managed by Hugging Face, allowing you to deploy models without dealing with containers and GPUs. ## When to use it? You should use Hugging Face Model Deployer: * if you want to deploy [Transformers, Sentence-Transformers, or Diffusion models](https://huggingface.co/docs/inference-endpoints/supported\_tasks) on dedicated and secure infrastructure. * if you prefer a fully-managed production solution for inference without the need to handle containers and GPUs. * if your goal is to turn your models into production-ready APIs with minimal infrastructure or MLOps involvement * Cost-effectiveness is crucial, and you want to pay only for the raw compute resources you use. * Enterprise security is a priority, and you need to deploy models into secure offline endpoints accessible only via a direct connection to your Virtual Private Cloud (VPCs). If you are looking for a more easy way to deploy your models locally, you can use the [MLflow Model Deployer](mlflow.md) flavor. ## How to deploy it? The Hugging Face Model Deployer flavor is provided by the Hugging Face ZenML integration, so you need to install it on your local machine to be able to deploy your models. You can do this by running the following command: ```bash zenml integration install huggingface -y ``` To register the Hugging Face model deployer with ZenML you need to run the following command: ```bash zenml model-deployer register --flavor=huggingface --token= --namespace= ``` Here, * `token` parameter is the Hugging Face authentication token. It can be managed through [Hugging Face settings](https://huggingface.co/settings/tokens). * `namespace` parameter is used for listing and creating the inference endpoints. It can take any of the following values, username or organization name or `*` depending on where the inference endpoint should be created. We can now use the model deployer in our stack. ```bash zenml stack update --model-deployer= ``` ## How to use it There are two mechanisms for using the Hugging Face model deployer integration: * Using the pre-built [huggingface\_model\_deployer\_step](https://github.com/zenml-io/zenml/blob/main/src/zenml/integrations/huggingface/steps/huggingface_deployer.py#L35) to deploy a Hugging Face model. * Running batch inference on a deployed Hugging Face model using the [HuggingFaceDeploymentService](https://github.com/zenml-io/zenml/blob/04cdf96576edd8fc615dceb7e0bf549301dc97bd/tests/integration/examples/huggingface/steps/prediction_service_loader/prediction_service_loader.py#L27) If you'd like to see this in action, check out this example of of [a deployment pipeline](https://github.com/zenml-io/zenml/blob/main/tests/integration/examples/huggingface/pipelines/deployment_pipelines/deployment_pipeline.py#L29) and [an inference pipeline](https://github.com/zenml-io/zenml/blob/main/tests/integration/examples/huggingface/pipelines/deployment_pipelines/inference_pipeline.py). ### Deploying a model The pre-built [huggingface\_model\_deployer\_step](https://github.com/zenml-io/zenml/blob/main/src/zenml/integrations/huggingface/steps/huggingface_deployer.py#L35) exposes a [`HuggingFaceServiceConfig`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-huggingface/#zenml.integrations.huggingface.services.huggingface_deployment.HuggingFaceServiceConfig) that you can use in your pipeline. Here is an example snippet: ```python from zenml import pipeline from zenml.config import DockerSettings from zenml.integrations.constants import HUGGINGFACE from zenml.integrations.huggingface.services import HuggingFaceServiceConfig from zenml.integrations.huggingface.steps import ( huggingface_model_deployer_step, ) docker_settings = DockerSettings( required_integrations=[HUGGINGFACE], ) @pipeline(enable_cache=True, settings={"docker": docker_settings}) def huggingface_deployment_pipeline( model_name: str = "hf", timeout: int = 1200, ): service_config = HuggingFaceServiceConfig(model_name=model_name) # Deployment step huggingface_model_deployer_step( service_config=service_config, timeout=timeout, ) ``` Within the `HuggingFaceServiceConfig` you can configure: * `model_name`: the name of the model in ZenML. * `endpoint_name`: the name of the inference endpoint. We add a prefix `zenml-` and first 8 characters of the service uuid as a suffix to the endpoint name. * `repository`: The repository name in the user’s namespace (`{username}/{model_id}`) or in the organization namespace (`{organization}/{model_id}`) from the Hugging Face hub. * `framework`: The machine learning framework used for the model (e.g. `"custom"`, `"pytorch"` ) * `accelerator`: The hardware accelerator to be used for inference. (e.g. `"cpu"`, `"gpu"`) * `instance_size`: The size of the instance to be used for hosting the model (e.g. `"large"`, `"xxlarge"`) * `instance_type`: Inference Endpoints offers a selection of curated CPU and GPU instances. (e.g. `"c6i"`, `"g5.12xlarge"`) * `region`: The cloud region in which the Inference Endpoint will be created (e.g. `"us-east-1"`, `"eu-west-1"` for `vendor = aws` and `"eastus"` for Microsoft Azure vendor.). * `vendor`: The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. `"aws"`). * `token`: The Hugging Face authentication token. It can be managed through [huggingface settings](https://huggingface.co/settings/tokens). The same token can be passed used while registering the Hugging Face model deployer. * `account_id`: (Optional) The account ID used to link a VPC to a private Inference Endpoint (if applicable). * `min_replica`: (Optional) The minimum number of replicas (instances) to keep running for the Inference Endpoint. Defaults to `0`. * `max_replica`: (Optional) The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to `1`. * `revision`: (Optional) The specific model revision to deploy on the Inference Endpoint for the Hugging Face repository . * `task`: Select a supported [Machine Learning Task](https://huggingface.co/docs/inference-endpoints/supported\_tasks). (e.g. `"text-classification"`, `"text-generation"`) * `custom_image`: (Optional) A custom Docker image to use for the Inference Endpoint. * `namespace`: The namespace where the Inference Endpoint will be created. The same namespace can be passed used while registering the Hugging Face model deployer. * `endpoint_type`: (Optional) The type of the Inference Endpoint, which can be `"protected"`, `"public"` (default) or `"private"`. For more information and a full list of configurable attributes of the Hugging Face Model Deployer, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-huggingface/) and Hugging Face endpoint [code](https://github.com/huggingface/huggingface_hub/blob/5e3b603ccc7cd6523d998e75f82848215abf9415/src/huggingface_hub/hf_api.py#L6957). ### Running inference on a provisioned inference endpoint The following code example shows how to run inference against a provisioned inference endpoint: ```python from typing import Annotated from zenml import step, pipeline from zenml.integrations.huggingface.model_deployers import HuggingFaceModelDeployer from zenml.integrations.huggingface.services import HuggingFaceDeploymentService # Load a prediction service deployed in another pipeline @step(enable_cache=False) def prediction_service_loader( pipeline_name: str, pipeline_step_name: str, running: bool = True, model_name: str = "default", ) -> HuggingFaceDeploymentService: """Get the prediction service started by the deployment pipeline. Args: pipeline_name: name of the pipeline that deployed the MLflow prediction server step_name: the name of the step that deployed the MLflow prediction server running: when this flag is set, the step only returns a running service model_name: the name of the model that is deployed """ # get the Hugging Face model deployer stack component model_deployer = HuggingFaceModelDeployer.get_active_model_deployer() # fetch existing services with same pipeline name, step name and model name existing_services = model_deployer.find_model_server( pipeline_name=pipeline_name, pipeline_step_name=pipeline_step_name, model_name=model_name, running=running, ) if not existing_services: raise RuntimeError( f"No Hugging Face inference endpoint deployed by step " f"'{pipeline_step_name}' in pipeline '{pipeline_name}' with name " f"'{model_name}' is currently running." ) return existing_services[0] # Use the service for inference @step def predictor( service: HuggingFaceDeploymentService, data: str ) -> Annotated[str, "predictions"]: """Run a inference request against a prediction service""" prediction = service.predict(data) return prediction @pipeline def huggingface_deployment_inference_pipeline( pipeline_name: str, pipeline_step_name: str = "huggingface_model_deployer_step", ): inference_data = ... model_deployment_service = prediction_service_loader( pipeline_name=pipeline_name, pipeline_step_name=pipeline_step_name, ) predictions = predictor(model_deployment_service, inference_data) ``` For more information and a full list of configurable attributes of the Hugging Face Model Deployer, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-huggingface/#zenml.integrations.huggingface.model\_deployers).
ZenML Scarf
================ File: docs/book/component-guide/model-deployers/mlflow.md ================ --- description: Deploying your models locally with MLflow. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # MLflow The MLflow Model Deployer is one of the available flavors of the [Model Deployer](./model-deployers.md) stack component. Provided with the MLflow integration it can be used to deploy and manage [MLflow models](https://www.mlflow.org/docs/latest/python\_api/mlflow.deployments.html) on a local running MLflow server. {% hint style="warning" %} The MLflow Model Deployer is not yet available for use in production. This is a work in progress and will be available soon. At the moment it is only available for use in a local development environment. {% endhint %} ## When to use it? MLflow is a popular open-source platform for machine learning. It's a great tool for managing the entire lifecycle of your machine learning. One of the most important features of MLflow is the ability to package your model and its dependencies into a single artifact that can be deployed to a variety of deployment targets. You should use the MLflow Model Deployer: * if you want to have an easy way to deploy your models locally and perform real-time predictions using the running MLflow prediction server. * if you are looking to deploy your models in a simple way without the need for a dedicated deployment environment like Kubernetes or advanced infrastructure configuration. If you are looking to deploy your models in a more complex way, you should use one of the other [Model Deployer Flavors](./model-deployers.md#model-deployers-flavors) available in ZenML. ## How do you deploy it? The MLflow Model Deployer flavor is provided by the MLflow ZenML integration, so you need to install it on your local machine to be able to deploy your models. You can do this by running the following command: ```bash zenml integration install mlflow -y ``` To register the MLflow model deployer with ZenML you need to run the following command: ```bash zenml model-deployer register mlflow_deployer --flavor=mlflow ``` The ZenML integration will provision a local MLflow deployment server as a daemon process that will continue to run in the background to serve the latest MLflow model. ## How do you use it? ### Deploy a logged model Following [MLflow's documentation](https://mlflow.org/docs/latest/deployment/deploy-model-locally.html#deploy-mlflow-model-as-a-local-inference-server), if we want to deploy a model as a local inference server, we need the model to be logged in the MLflow experiment tracker first. Once the model is logged, we can use the model URI either from the artifact path saved with the MLflow run or using model name and version if a model is registered in the MLflow model registry. In the following examples, we will show how to deploy a model using the MLflow Model Deployer, in two different scenarios: 1. We already know the logged model URI and we want to deploy it as a local inference server. ```python from zenml import pipeline, step, get_step_context from zenml.client import Client @step def deploy_model() -> Optional[MLFlowDeploymentService]: # Deploy a model using the MLflow Model Deployer zenml_client = Client() model_deployer = zenml_client.active_stack.model_deployer mlflow_deployment_config = MLFlowDeploymentConfig( name: str = "mlflow-model-deployment-example", description: str = "An example of deploying a model using the MLflow Model Deployer", pipeline_name: str = get_step_context().pipeline_name, pipeline_step_name: str = get_step_context().step_name, model_uri: str = "runs://model" or "models://", model_name: str = "model", workers: int = 1 mlserver: bool = False timeout: int = DEFAULT_SERVICE_START_STOP_TIMEOUT ) service = model_deployer.deploy_model( config=mlflow_deployment_config, service_type=MLFlowDeploymentService.SERVICE_TYPE ) logger.info(f"The deployed service info: {model_deployer.get_model_server_info(service)}") return service ``` 2. We don't know the logged model URI, since the model was logged in a previous step. We want to deploy the model as a local inference server. ZenML provides set of functionalities that would make it easier to get the model URI from the current run and deploy it. ```python from zenml import pipeline, step, get_step_context from zenml.client import Client from mlflow.tracking import MlflowClient, artifact_utils @step def deploy_model() -> Optional[MLFlowDeploymentService]: # Deploy a model using the MLflow Model Deployer zenml_client = Client() model_deployer = zenml_client.active_stack.model_deployer experiment_tracker = zenml_client.active_stack.experiment_tracker # Let's get the run id of the current pipeline mlflow_run_id = experiment_tracker.get_run_id( experiment_name=get_step_context().pipeline_name, run_name=get_step_context().run_name, ) # Once we have the run id, we can get the model URI using mlflow client experiment_tracker.configure_mlflow() client = MlflowClient() model_name = "model" # set the model name that was logged model_uri = artifact_utils.get_artifact_uri( run_id=mlflow_run_id, artifact_path=model_name ) mlflow_deployment_config = MLFlowDeploymentConfig( name: str = "mlflow-model-deployment-example", description: str = "An example of deploying a model using the MLflow Model Deployer", pipeline_name: str = get_step_context().pipeline_name, pipeline_step_name: str = get_step_context().step_name, model_uri: str = model_uri, model_name: str = model_name, workers: int = 1, mlserver: bool = False, timeout: int = 300, ) service = model_deployer.deploy_model( config=mlflow_deployment_config, service_type=MLFlowDeploymentService.SERVICE_TYPE ) return service ``` #### Configuration Within the `MLFlowDeploymentService` you can configure: * `name`: The name of the deployment. * `description`: The description of the deployment. * `pipeline_name`: The name of the pipeline that deployed the MLflow prediction server. * `pipeline_step_name`: The name of the step that deployed the MLflow prediction server. * `model_name`: The name of the model that is deployed in case of model registry the name must be a valid registered model name. * `model_version`: The version of the model that is deployed in case of model registry the version must be a valid registered model version. * `silent_daemon`: set to True to suppress the output of the daemon (i.e., redirect stdout and stderr to /dev/null). If False, the daemon output will be redirected to a log file. * `blocking`: set to True to run the service in the context of the current process and block until the service is stopped instead of running the service as a daemon process. Useful for operating systems that do not support daemon processes. * `model_uri`: The URI of the model to be deployed. This can be a local file path, a run ID, or a model name and version. * `workers`: The number of workers to be used by the MLflow prediction server. * `mlserver`: If True, the MLflow prediction server will be started as a MLServer instance. * `timeout`: The timeout in seconds to wait for the MLflow prediction server to start or stop. ### Run inference on a deployed model The following code example shows how you can load a deployed model in Python and run inference against it: 1. Load a prediction service deployed in another pipeline ```python import json import requests from zenml import step from zenml.integrations.mlflow.model_deployers.mlflow_model_deployer import ( MLFlowModelDeployer, ) from zenml.integrations.mlflow.services import MLFlowDeploymentService # Load a prediction service deployed in another pipeline @step(enable_cache=False) def prediction_service_loader( pipeline_name: str, pipeline_step_name: str, model_name: str = "model", ) -> None: """Get the prediction service started by the deployment pipeline. Args: pipeline_name: name of the pipeline that deployed the MLflow prediction server step_name: the name of the step that deployed the MLflow prediction server running: when this flag is set, the step only returns a running service model_name: the name of the model that is deployed """ # get the MLflow model deployer stack component model_deployer = MLFlowModelDeployer.get_active_model_deployer() # fetch existing services with same pipeline name, step name and model name existing_services = model_deployer.find_model_server( pipeline_name=pipeline_name, pipeline_step_name=pipeline_step_name, model_name=model_name, ) if not existing_services: raise RuntimeError( f"No MLflow prediction service deployed by step " f"'{pipeline_step_name}' in pipeline '{pipeline_name}' with name " f"'{model_name}' is currently running." ) service = existing_services[0] # Let's try run a inference request against the prediction service payload = json.dumps( { "inputs": {"messages": [{"role": "user", "content": "Tell a joke!"}]}, "params": { "temperature": 0.5, "max_tokens": 20, }, } ) response = requests.post( url=service.get_prediction_url(), data=payload, headers={"Content-Type": "application/json"}, ) response.json() ``` 2. Within the same pipeline, use the service from previous step to run inference this time using pre-built predict method ```python from typing_extensions import Annotated import numpy as np from zenml import step from zenml.integrations.mlflow.services import MLFlowDeploymentService # Use the service for inference @step def predictor( service: MLFlowDeploymentService, data: np.ndarray, ) -> Annotated[np.ndarray, "predictions"]: """Run a inference request against a prediction service""" prediction = service.predict(data) prediction = prediction.argmax(axis=-1) return prediction ``` For more information and a full list of configurable attributes of the MLflow Model Deployer, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-mlflow/#zenml.integrations.mlflow.model\_deployers) .
ZenML Scarf
================ File: docs/book/component-guide/model-deployers/model-deployers.md ================ --- icon: rocket description: Deploying your models and serve real-time predictions. --- # Model Deployers Model Deployment is the process of making a machine learning model available to make predictions and decisions on real-world data. Getting predictions from trained models can be done in different ways depending on the use case, a batch prediction is used to generate predictions for a large amount of data at once, while a real-time prediction is used to generate predictions for a single data point at a time. Model deployers are stack components responsible for serving models on a real-time or batch basis. Online serving is the process of hosting and loading machine-learning models as part of a managed web service and providing access to the models through an API endpoint like HTTP or GRPC. Once deployed, model inference can be triggered at any time, and you can send inference requests to the model through the web service's API and receive fast, low-latency responses. Batch inference or offline inference is the process of making a machine learning model make predictions on a batch of observations. This is useful for generating predictions for a large amount of data at once. The predictions are usually stored as files or in a database for end users or business applications. ### When to use it? The model deployers are optional components in the ZenML stack. They are used to deploy machine learning models to a target environment, either a development (local) or a production (Kubernetes or cloud) environment. The model deployers are mainly used to deploy models for real-time inference use cases. With the model deployers and other stack components, you can build pipelines that are continuously trained and deployed to production. ### How model deployers slot into the stack Here is an architecture diagram that shows how model deployers fit into the overall story of a remote stack. ![Model Deployers](../../.gitbook/assets/Remote_with_deployer.png) #### Model Deployers Flavors ZenML comes with a `local` MLflow model deployer which is a simple model deployer that deploys models to a local MLflow server. Additional model deployers that can be used to deploy models on production environments are provided by integrations: | Model Deployer | Flavor | Integration | Notes | |------------------------------------|-----------|---------------|------------------------------------------------------------------------------| | [MLflow](mlflow.md) | `mlflow` | `mlflow` | Deploys ML Model locally | | [BentoML](bentoml.md) | `bentoml` | `bentoml` | Build and Deploy ML models locally or for production grade (Cloud, K8s) | | [Seldon Core](seldon.md) | `seldon` | `seldon Core` | Built on top of Kubernetes to deploy models for production grade environment | | [Hugging Face](huggingface.md) | `huggingface` | `huggingface` | Deploys ML model on Hugging Face Inference Endpoints | | [Databricks](databricks.md) | `databricks` | `databricks` | Deploying models to Databricks Inference Endpoints with Databricks | | [vLLM](vllm.md) | `vllm` | `vllm` | Deploys LLM using vLLM locally | | [Custom Implementation](custom.md) | _custom_ | | Extend the Artifact Store abstraction and provide your own implementation | {% hint style="info" %} Every model deployer may have different attributes that must be configured in order to interact with the model serving tool, framework, or platform (e.g. hostnames, URLs, references to credentials, and other client-related configuration parameters). The following example shows the configuration of the MLflow and Seldon Core model deployers: ```shell # Configure MLflow model deployer zenml model-deployer register mlflow --flavor=mlflow # Configure Seldon Core model deployer zenml model-deployer register seldon --flavor=seldon \ --kubernetes_context=zenml-eks --kubernetes_namespace=zenml-workloads \ --base_url=http://abb84c444c7804aa98fc8c097896479d-377673393.us-east-1.elb.amazonaws.com ... ``` {% endhint %} #### The role that a model deployer plays in a ZenML Stack * Seamless Model Deployment: Facilitates the deployment of machine learning models to various serving environments, such as local servers, Kubernetes clusters, or cloud platforms, ensuring that models can be deployed and managed efficiently in accordance with the specific requirements of the serving infrastructure by holds all the stack-related configuration attributes required to interact with the remote model serving tool, service, or platform (e.g. hostnames, URLs, references to credentials, and other client-related configuration parameters). The following are examples of configuring the MLflow and Seldon Core Model Deployers and registering them as a Stack component: ```bash zenml integration install mlflow zenml model-deployer register mlflow --flavor=mlflow zenml stack register local_with_mlflow -m default -a default -o default -d mlflow --set ``` ```bash zenml integration install seldon zenml model-deployer register seldon --flavor=seldon \ --kubernetes_context=zenml-eks --kubernetes_namespace=zenml-workloads \ --base_url=http://abb84c444c7804aa98fc8c097896479d-377673393.us-east-1.elb.amazonaws.com ... zenml stack register seldon_stack -m default -a aws -o default -d seldon ``` * Lifecycle Management: Provides mechanisms for comprehensive lifecycle management of model servers, including the ability to start, stop, and delete model servers, as well as to update existing servers with new model versions, thereby optimizing resource utilization and facilitating continuous delivery of model updates. Some core methods that can be used to interact with the remote model server include: `deploy_model` - Deploys a model to the serving environment and returns a Service object that represents the deployed model server. `find_model_server` - Finds and returns a list of Service objects that represent model servers that have been deployed to the serving environment, the services are stored in the DB and can be used as a reference to know what and where the model is deployed. `stop_model_server` - Stops a model server that is currently running in the serving environment. `start_model_server` - Starts a model server that has been stopped in the serving environment. `delete_model_server` - Deletes a model server from the serving environment and from the DB. {% hint style="info" %} ZenML uses the Service object to represent a model server that has been deployed to a serving environment. The Service object is saved in the DB and can be used as a reference to know what and where the model is deployed. The Service object consists of 2 main attributes, the `config` and the `status`. The `config` attribute holds all the deployment configuration attributes required to create a new deployment, while the `status` attribute holds the operational status of the deployment, such as the last error message, the prediction URL, and the deployment status. {% endhint %} ```python from zenml.integrations.huggingface.model_deployers import HuggingFaceModelDeployer model_deployer = HuggingFaceModelDeployer.get_active_model_deployer() services = model_deployer.find_model_server( pipeline_name="LLM_pipeline", pipeline_step_name="huggingface_model_deployer_step", model_name="LLAMA-7B", ) if services: if services[0].is_running: print( f"Model server {services[0].config['model_name']} is running at {services[0].status['prediction_url']}" ) else: print(f"Model server {services[0].config['model_name']} is not running") model_deployer.start_model_server(services[0]) else: print("No model server found") service = model_deployer.deploy_model( pipeline_name="LLM_pipeline", pipeline_step_name="huggingface_model_deployer_step", model_name="LLAMA-7B", model_uri="s3://zenprojects/huggingface_model_deployer_step/output/884/huggingface", revision="main", task="text-classification", region="us-east-1", vendor="aws", token="huggingface_token", namespace="zenml-workloads", endpoint_type="public", ) print(f"Model server {service.config['model_name']} is deployed at {service.status['prediction_url']}") ``` #### How to Interact with a model deployer after deployment? When a Model Deployer is part of the active ZenML Stack, it is also possible to interact with it from the CLI to list, start, stop, or delete the model servers that is managed: ``` $ zenml model-deployer models list ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ STATUS β”‚ UUID β”‚ PIPELINE_NAME β”‚ PIPELINE_STEP_NAME ┃ ┠────────┼──────────────────────────────────────┼────────────────────────────────┼────────────────────────────┨ ┃ βœ… β”‚ 8cbe671b-9fce-4394-a051-68e001f92765 β”‚ seldon_deployment_pipeline β”‚ seldon_model_deployer_step ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ $ zenml model-deployer models describe 8cbe671b-9fce-4394-a051-68e001f92765 Properties of Served Model 8cbe671b-9fce-4394-a051-68e001f92765 ┏━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ MODEL SERVICE PROPERTY β”‚ VALUE ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────┨ ┃ MODEL_NAME β”‚ mnist ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────┨ ┃ MODEL_URI β”‚ s3://zenprojects/seldon_model_deployer_step/output/884/seldon ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────┨ ┃ PIPELINE_NAME β”‚ seldon_deployment_pipeline ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────┨ ┃ RUN_NAME β”‚ seldon_deployment_pipeline-11_Apr_22-09_39_27_648527 ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────┨ ┃ PIPELINE_STEP_NAME β”‚ seldon_model_deployer_step ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────┨ ┃ PREDICTION_URL β”‚ http://abb84c444c7804aa98fc8c097896479d-377673393.us-east-1.elb.amazonaws.com/seldon/… ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────┨ ┃ SELDON_DEPLOYMENT β”‚ zenml-8cbe671b-9fce-4394-a051-68e001f92765 ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────┨ ┃ STATUS β”‚ βœ… ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────┨ ┃ STATUS_MESSAGE β”‚ Seldon Core deployment 'zenml-8cbe671b-9fce-4394-a051-68e001f92765' is available ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────┨ ┃ UUID β”‚ 8cbe671b-9fce-4394-a051-68e001f92765 ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ $ zenml model-deployer models get-url 8cbe671b-9fce-4394-a051-68e001f92765 Prediction URL of Served Model 8cbe671b-9fce-4394-a051-68e001f92765 is: http://abb84c444c7804aa98fc8c097896479d-377673393.us-east-1.elb.amazonaws.com/seldon/zenml-workloads/zenml-8cbe67 1b-9fce-4394-a051-68e001f92765/api/v0.1/predictions $ zenml model-deployer models delete 8cbe671b-9fce-4394-a051-68e001f92765 ``` In Python, you can alternatively discover the prediction URL of a deployed model by inspecting the metadata of the step that deployed the model: ```python from zenml.client import Client pipeline_run = Client().get_pipeline_run("") deployer_step = pipeline_run.steps[""] deployed_model_url = deployer_step.run_metadata["deployed_model_url"].value ``` The ZenML integrations that provide Model Deployer stack components also include standard pipeline steps that can directly be inserted into any pipeline to achieve a continuous model deployment workflow. These steps take care of all the aspects of continuously deploying models to an external server and saving the Service configuration into the Artifact Store, where they can be loaded at a later time and re-create the initial conditions used to serve a particular model.
ZenML Scarf
================ File: docs/book/component-guide/model-deployers/seldon.md ================ --- description: Deploying models to Kubernetes with Seldon Core. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Seldon [Seldon Core](https://github.com/SeldonIO/seldon-core) is a production grade source-available model serving platform. It packs a wide range of features built around deploying models to REST/GRPC microservices that include monitoring and logging, model explainers, outlier detectors and various continuous deployment strategies such as A/B testing, canary deployments and more. Seldon Core also comes equipped with a set of built-in model server implementations designed to work with standard formats for packaging ML models that greatly simplify the process of serving models for real-time inference. {% hint style="warning" %} The Seldon Core model deployer integration is currently not supported under **MacOS**. {% endhint %} ## When to use it? [Seldon Core](https://github.com/SeldonIO/seldon-core) is a production-grade source-available model serving platform. It packs a wide range of features built around deploying models to REST/GRPC microservices that include monitoring and logging, model explainers, outlier detectors, and various continuous deployment strategies such as A/B testing, canary deployments, and more. Seldon Core also comes equipped with a set of built-in model server implementations designed to work with standard formats for packaging ML models that greatly simplify the process of serving models for real-time inference. You should use the Seldon Core Model Deployer: * If you are looking to deploy your model on a more advanced infrastructure like Kubernetes. * If you want to handle the lifecycle of the deployed model with no downtime, including updating the runtime graph, scaling, monitoring, and security. * Looking for more advanced API endpoints to interact with the deployed model, including REST and GRPC endpoints. * If you want more advanced deployment strategies like A/B testing, canary deployments, and more. * if you have a need for a more complex deployment process that can be customized by the advanced inference graph that includes custom [TRANSFORMER](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/overview.html) and [ROUTER](https://docs.seldon.io/projects/seldon-core/en/latest/analytics/routers.html?highlight=routers). If you are looking for a more easy way to deploy your models locally, you can use the [MLflow Model Deployer](mlflow.md) flavor. ## How to deploy it? ZenML provides a Seldon Core flavor build on top of the Seldon Core Integration to allow you to deploy and use your models in a production-grade environment. In order to use the integration you need to install it on your local machine to be able to register a Seldon Core Model deployer with ZenML and add it to your stack: ```bash zenml integration install seldon -y ``` To deploy and make use of the Seldon Core integration we need to have the following prerequisites: 1. access to a Kubernetes cluster. This can be configured using the `kubernetes_context` configuration attribute to point to a local `kubectl` context or an in-cluster configuration, but the recommended approach is to [use a Service Connector](seldon.md#using-a-service-connector) to link the Seldon Deployer Stack Component to a Kubernetes cluster. 2. Seldon Core needs to be preinstalled and running in the target Kubernetes cluster. Check out the [official Seldon Core installation instructions](https://github.com/SeldonIO/seldon-core/tree/master/examples/auth#demo-setup) or the [EKS installation example below](seldon.md#installing-seldon-core-eg-in-an-eks-cluster). 3. models deployed with Seldon Core need to be stored in some form of persistent shared storage that is accessible from the Kubernetes cluster where Seldon Core is installed (e.g. AWS S3, GCS, Azure Blob Storage, etc.). You can use one of the supported [remote artifact store flavors](../artifact-stores/artifact-stores.md) to store your models as part of your stack. For a smoother experience running Seldon Core with a cloud artifact store, we also recommend configuring explicit credentials for the artifact store. The Seldon Core model deployer knows how to automatically convert those credentials in the format needed by Seldon Core model servers to authenticate to the storage back-end where models are stored. Since the Seldon Model Deployer is interacting with the Seldon Core model server deployed on a Kubernetes cluster, you need to provide a set of configuration parameters. These parameters are: * kubernetes\_context: the Kubernetes context to use to contact the remote Seldon Core installation. If not specified, the active Kubernetes context is used or the in-cluster configuration is used if the model deployer is running in a Kubernetes cluster. The recommended approach is to [use a Service Connector](seldon.md#using-a-service-connector) to link the Seldon Deployer Stack Component to a Kubernetes cluster and to skip this parameter. * kubernetes\_namespace: the Kubernetes namespace where the Seldon Core deployment servers are provisioned and managed by ZenML. If not specified, the namespace set in the current configuration is used. * base\_url: the base URL of the Kubernetes ingress used to expose the Seldon Core deployment servers. In addition to these parameters, the Seldon Core Model Deployer may also require additional configuration to be set up to allow it to authenticate to the remote artifact store or persistent storage service where model artifacts are located. This is covered in the [Managing Seldon Core Authentication](seldon.md#managing-seldon-core-authentication) section. ### Seldon Core Installation Example The following example briefly shows how you can install Seldon in an EKS Kubernetes cluster. It assumes that the EKS cluster itself is already set up and configured with IAM access. For more information or tutorials for other clouds, check out the [official Seldon Core installation instructions](https://github.com/SeldonIO/seldon-core/tree/master/examples/auth#demo-setup). 1. Configure EKS cluster access locally, e.g: ```bash aws eks --region us-east-1 update-kubeconfig --name zenml-cluster --alias zenml-eks ``` 2. Install Istio 1.5.0 (required for the latest Seldon Core version): ```bash curl -L [https://istio.io/downloadIstio](https://istio.io/downloadIstio) | ISTIO_VERSION=1.5.0 sh - cd istio-1.5.0/ bin/istioctl manifest apply --set profile=demo ``` 3. Set up an Istio gateway for Seldon Core: ```bash curl https://raw.githubusercontent.com/SeldonIO/seldon-core/master/notebooks/resources/seldon-gateway.yaml | kubectl apply -f - ``` 4. Install Seldon Core: ```bash helm install seldon-core seldon-core-operator \ --repo https://storage.googleapis.com/seldon-charts \ --set usageMetrics.enabled=true \ --set istio.enabled=true \ --namespace seldon-system ``` 5. Test that the installation is functional ```bash kubectl apply -f iris.yaml ``` with `iris.yaml` defined as follows: ```yaml apiVersion: machinelearning.seldon.io/v1 kind: SeldonDeployment metadata: name: iris-model namespace: default spec: name: iris predictors: - graph: implementation: SKLEARN_SERVER modelUri: gs://seldon-models/v1.14.0-dev/sklearn/iris name: classifier name: default replicas: 1 ``` Then extract the URL where the model server exposes its prediction API: ```bash export INGRESS_HOST=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].hostname}') ``` And use curl to send a test prediction API request to the server: ```bash curl -X POST http://$INGRESS_HOST/seldon/default/iris-model/api/v1.0/predictions \ -H 'Content-Type: application/json' \ -d '{ "data": { "ndarray": [[1,2,3,4]] } }' ``` ### Using a Service Connector To set up the Seldon Core Model Deployer to authenticate to a remote Kubernetes cluster, it is recommended to leverage the many features provided by [the Service Connectors](../../how-to/infrastructure-deployment/auth-management/README.md) such as auto-configuration, local client login, best security practices regarding long-lived credentials and fine-grained access control and reusing the same credentials across multiple stack components. Depending on where your target Kubernetes cluster is running, you can use one of the following Service Connectors: * [the AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md), if you are using an AWS EKS cluster. * [the GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md), if you are using a GKE cluster. * [the Azure Service Connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md), if you are using an AKS cluster. * [the generic Kubernetes Service Connector](../../how-to/infrastructure-deployment/auth-management/kubernetes-service-connector.md) for any other Kubernetes cluster. If you don't already have a Service Connector configured in your ZenML deployment, you can register one using the interactive CLI command. You have the option to configure a Service Connector that can be used to access more than one Kubernetes cluster or even more than one type of cloud resource: ```sh zenml service-connector register -i ``` A non-interactive CLI example that leverages [the AWS CLI configuration](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) on your local machine to auto-configure an AWS Service Connector targeting a single EKS cluster is: ```sh zenml service-connector register --type aws --resource-type kubernetes-cluster --resource-name --auto-configure ``` {% code title="Example Command Output" %} ``` $ zenml service-connector register eks-zenhacks --type aws --resource-type kubernetes-cluster --resource-id zenhacks-cluster --auto-configure β Ό Registering service connector 'eks-zenhacks'... Successfully registered service connector `eks-zenhacks` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────┨ ┃ πŸŒ€ kubernetes-cluster β”‚ zenhacks-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} Alternatively, you can configure a Service Connector through the ZenML dashboard: ![AWS Service Connector Type](../../.gitbook/assets/aws-service-connector-type.png) ![AWS EKS Service Connector Configuration](../../.gitbook/assets/aws-eks-service-connector-configuration.png) > **Note**: Please remember to grant the entity associated with your cloud credentials permissions to access the Kubernetes cluster and to list accessible Kubernetes clusters. For a full list of permissions required to use a AWS Service Connector to access one or more Kubernetes cluster, please refer to the [documentation for your Service Connector of choice](../../how-to/infrastructure-deployment/auth-management/README.md) or read the documentation available in the interactive CLI commands and dashboard. The Service Connectors supports many different authentication methods with different levels of security and convenience. You should pick the one that best fits your use-case. If you already have one or more Service Connectors configured in your ZenML deployment, you can check which of them can be used to access the Kubernetes cluster that you want to use for your Seldon Core Model Deployer by running e.g.: ```sh zenml service-connector list-resources --resource-type kubernetes-cluster ``` {% code title="Example Command Output" %} ``` The following 'kubernetes-cluster' resources can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────────────┼───────────────────────────────────────────────┨ ┃ bdf1dc76-e36b-4ab4-b5a6-5a9afea4822f β”‚ eks-zenhacks β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ zenhacks-cluster ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────────────┼───────────────────────────────────────────────┨ ┃ b57f5f5c-0378-434c-8d50-34b492486f30 β”‚ gcp-multi β”‚ πŸ”΅ gcp β”‚ πŸŒ€ kubernetes-cluster β”‚ zenml-test-cluster ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────────────┼───────────────────────────────────────────────┨ ┃ d6fc6004-eb76-4fd7-8fa1-ec600cced680 β”‚ azure-multi β”‚ πŸ‡¦ azure β”‚ πŸŒ€ kubernetes-cluster β”‚ demo-zenml-demos/demo-zenml-terraform-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} After having set up or decided on a Service Connector to use to connect to the target Kubernetes cluster where Seldon Core is installed, you can register the Seldon Core Model Deployer as follows: ```sh # Register the Seldon Core Model Deployer zenml model-deployer register --flavor=seldon \ --kubernetes_namespace= \ --base_url=http://$INGRESS_HOST # Connect the Seldon Core Model Deployer to the target cluster via a Service Connector zenml model-deployer connect -i ``` A non-interactive version that connects the Seldon Core Model Deployer to a target Kubernetes cluster through a Service Connector: ```sh zenml model-deployer connect --connector --resource-id ``` {% code title="Example Command Output" %} ``` $ zenml model-deployer connect seldon-test --connector gcp-multi --resource-id zenml-test-cluster Successfully connected model deployer `seldon-test` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────────────┼────────────────────┨ ┃ b57f5f5c-0378-434c-8d50-34b492486f30 β”‚ gcp-multi β”‚ πŸ”΅ gcp β”‚ πŸŒ€ kubernetes-cluster β”‚ zenml-test-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┛ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} A similar experience is available when you configure the Seldon Core Model Deployer through the ZenML dashboard: ![Seldon Core Model Deployer Configuration](../../.gitbook/assets/seldon-model-deployer-service-connector.png) ### Managing Seldon Core Authentication The Seldon Core Model Deployer requires access to the persistent storage where models are located. In most cases, you will use the Seldon Core model deployer to serve models that are trained through ZenML pipelines and stored in the ZenML Artifact Store, which implies that the Seldon Core model deployer needs to access the Artifact Store. If Seldon Core is already running in the same cloud as the Artifact Store (e.g. S3 and an EKS cluster for AWS, or GCS and a GKE cluster for GCP), there are ways of configuring cloud workloads to have implicit access to other cloud resources like persistent storage without requiring explicit credentials. However, if Seldon Core is running in a different cloud, or on-prem, or if implicit in-cloud workload authentication is not enabled, then you need to configure explicit credentials for the Artifact Store to allow other components like the Seldon Core model deployer to authenticate to it. Every cloud Artifact Store flavor supports some way of configuring explicit credentials and this is documented for each individual flavor in the [Artifact Store documentation](../artifact-stores/artifact-stores.md). When explicit credentials are configured in the Artifact Store, the Seldon Core Model Deployer doesn't need any additional configuration and will use those credentials automatically to authenticate to the same persistent storage service used by the Artifact Store. If the Artifact Store doesn't have explicit credentials configured, then Seldon Core will default to using whatever implicit authentication method is available in the Kubernetes cluster where it is running. For example, in AWS this means using the IAM role attached to the EC2 or EKS worker nodes, and in GCP this means using the service account attached to the GKE worker nodes. {% hint style="warning" %} If the Artifact Store used in combination with the Seldon Core Model Deployer in the same ZenML stack does not have explicit credentials configured, then the Seldon Core Model Deployer might not be able to authenticate to the Artifact Store which will cause the deployed model servers to fail. To avoid this, we recommend that you use Artifact Stores with explicit credentials in the same stack as the Seldon Core Model Deployer. Alternatively, if you're running Seldon Core in one of the cloud providers, you should configure implicit authentication for the Kubernetes nodes. {% endhint %} If you want to use a custom persistent storage with Seldon Core, or if you prefer to manually manage the authentication credentials attached to the Seldon Core model servers, you can use the approach described in the next section. **Advanced: Configuring a Custom Seldon Core Secret** The Seldon Core model deployer stack component allows configuring an additional `secret` attribute that can be used to specify custom credentials that Seldon Core should use to authenticate to the persistent storage service where models are located. This is useful if you want to connect Seldon Core to a persistent storage service that is not supported as a ZenML Artifact Store, or if you don't want to configure or use the same credentials configured for your Artifact Store. The `secret` attribute must be set to the name of [a ZenML secret](../../how-to/project-setup-and-management/interact-with-secrets.md) containing credentials configured in the format supported by Seldon Core. {% hint style="info" %} This method is not recommended, because it limits the Seldon Core model deployer to a single persistent storage service, whereas using the Artifact Store credentials gives you more flexibility in combining the Seldon Core model deployer with any Artifact Store in the same ZenML stack. {% endhint %} Seldon Core model servers use [`rclone`](https://rclone.org/) to connect to persistent storage services and the credentials that can be configured in the ZenML secret must also be in the configuration format supported by `rclone`. This section covers a few common use cases and provides examples of how to configure the ZenML secret to support them, but for more information on supported configuration options, you can always refer to the [`rclone` documentation for various providers](https://rclone.org/).
Seldon Core Authentication Secret Examples Example of configuring a Seldon Core secret for AWS S3: ```shell zenml secret create s3-seldon-secret \ --rclone_config_s3_type="s3" \ # set to 's3' for S3 storage. --rclone_config_s3_provider="aws" \ # the S3 provider (e.g. aws, Ceph, Minio). --rclone_config_s3_env_auth=False \ # set to true to use implicit AWS authentication from EC2/ECS meta data # (i.e. with IAM roles configuration). Only applies if access_key_id and secret_access_key are blank. --rclone_config_s3_access_key_id="" \ # AWS Access Key ID. --rclone_config_s3_secret_access_key="" \ # AWS Secret Access Key. --rclone_config_s3_session_token="" \ # AWS Session Token. --rclone_config_s3_region="" \ # region to connect to. --rclone_config_s3_endpoint="" \ # S3 API endpoint. # Alternatively for providing key-value pairs, you can utilize the '--values' option by specifying a file path containing # key-value pairs in either JSON or YAML format. # File content example: {"rclone_config_s3_type":"s3",...} zenml secret create s3-seldon-secret \ --values=@path/to/file.json ``` Example of configuring a Seldon Core secret for GCS: ```shell zenml secret create gs-seldon-secret \ --rclone_config_gs_type="google cloud storage" \ # set to 'google cloud storage' for GCS storage. --rclone_config_gs_client_secret="" \ # OAuth client secret. --rclone_config_gs_token="" \ # OAuth Access Token as a JSON blob. --rclone_config_gs_project_number="" \ # project number. --rclone_config_gs_service_account_credentials="" \ #service account credentials JSON blob. --rclone_config_gs_anonymous=False \ # Access public buckets and objects without credentials. # Set to True if you just want to download files and don't configure credentials. --rclone_config_gs_auth_url="" \ # auth server URL. # Alternatively for providing key-value pairs, you can utilize the '--values' option by specifying a file path containing # key-value pairs in either JSON or YAML format. # File content example: {"rclone_config_gs_type":"google cloud storage",...} zenml secret create gs-seldon-secret \ --values=@path/to/file.json ``` Example of configuring a Seldon Core secret for Azure Blob Storage: ```shell zenml secret create az-seldon-secret \ --rclone_config_az_type="azureblob" \ # set to 'azureblob' for Azure Blob Storage. --rclone_config_az_account="" \ # storage Account Name. Leave blank to # use SAS URL or MSI. --rclone_config_az_key="" \ # storage Account Key. Leave blank to # use SAS URL or MSI. --rclone_config_az_sas_url="" \ # SAS URL for container level access # only. Leave blank if using account/key or MSI. --rclone_config_az_use_msi="" \ # use a managed service identity to # authenticate (only works in Azure). --rclone_config_az_client_id="" \ # client ID of the service principal # to use for authentication. --rclone_config_az_client_secret="" \ # client secret of the service # principal to use for authentication. --rclone_config_az_tenant="" \ # tenant ID of the service principal # to use for authentication. # Alternatively for providing key-value pairs, you can utilize the '--values' option by specifying a file path containing # key-value pairs in either JSON or YAML format. # File content example: {"rclone_config_az_type":"azureblob",...} zenml secret create az-seldon-secret \ --values=@path/to/file.json ```
## How do you use it? ### Requirements To run pipelines that deploy models to Seldon, you need the following tools installed locally: * [Docker](https://www.docker.com) * [K3D](https://k3d.io/v5.2.1/#installation) (can be installed by running `curl -s https://raw.githubusercontent.com/rancher/k3d/main/install.sh | bash`). ### Stack Component Registration For registering the model deployer, we need the URL of the Istio Ingress Gateway deployed on the Kubernetes cluster. We can get this URL by running the following command (assuming that the service name is `istio-ingressgateway`, deployed in the `istio-system` namespace): ```bash # For GKE clusters, the host is the GKE cluster IP address. export INGRESS_HOST=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}') # For EKS clusters, the host is the EKS cluster IP hostname. export INGRESS_HOST=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].hostname}') ``` Now register the model deployer: > **Note**: If you chose to configure your own custom credentials to authenticate to the persistent storage service where models are stored, as covered in the [Advanced: Configuring a Custom Seldon Core Secret](seldon.md#managing-seldon-core-authentication) section, you will need to specify a ZenML secret reference when you configure the Seldon Core model deployer below: > > ```shell > zenml model-deployer register seldon_deployer --flavor=seldon \ > --kubernetes_context= \ > --kubernetes_namespace= \ > --base_url=http://$INGRESS_HOST \ > --secret= > ``` ```bash # Register the Seldon Core Model Deployer zenml model-deployer register seldon_deployer --flavor=seldon \ --kubernetes_context= \ --kubernetes_namespace= \ --base_url=http://$INGRESS_HOST \ ``` We can now use the model deployer in our stack. ```bash zenml stack update seldon_stack --model-deployer=seldon_deployer ``` See the [seldon\_model\_deployer\_step](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-seldon/#zenml.integrations.seldon.steps.seldon\_deployer.seldon\_model\_deployer\_step) for an example of using the Seldon Core Model Deployer to deploy a model inside a ZenML pipeline step. ### Configuration Within the `SeldonDeploymentConfig` you can configure: * `model_name`: the name of the model in the Seldon cluster and in ZenML. * `replicas`: the number of replicas with which to deploy the model * `implementation`: the type of Seldon inference server to use for the model. The implementation type can be one of the following: `TENSORFLOW_SERVER`, `SKLEARN_SERVER`, `XGBOOST_SERVER`, `custom`. * `parameters`: an optional list of parameters (`SeldonDeploymentPredictorParameter`) to pass to the deployment predictor in the form of: * `name` * `type` * `value` * `resources`: the resources to be allocated to the model. This can be configured by passing a `SeldonResourceRequirements` object with the `requests` and `limits` properties. The values for these properties can be a dictionary with the `cpu` and `memory` keys. The values for these keys can be a string with the amount of CPU and memory to be allocated to the model. * `serviceAccount` The name of the Service Account applied to the deployment. For more information and a full list of configurable attributes of the Seldon Core Model Deployer, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-seldon/#zenml.integrations.seldon.model\_deployers) . ### Custom Code Deployment ZenML enables you to deploy your pre- and post-processing code into the deployment environment together with the model by defining a custom predict function that will be wrapped in a Docker container and executed on the model deployment server, e.g.: ```python def custom_predict( model: Any, request: Array_Like, ) -> Array_Like: """Custom Prediction function. The custom predict function is the core of the custom deployment, the function is called by the custom deployment class defined for the serving tool. The current implementation requires the function to get the model loaded in the memory and a request with the data to predict. Args: model: The model to use for prediction. request: The prediction response of the model is an array-like format. Returns: The prediction in an array-like format. """ inputs = [] for instance in request: input = np.array(instance) if not isinstance(input, np.ndarray): raise Exception("The request must be a NumPy array") processed_input = pre_process(input) prediction = model.predict(processed_input) postprocessed_prediction = post_process(prediction) inputs.append(postprocessed_prediction) return inputs def pre_process(input: np.ndarray) -> np.ndarray: """Pre process the data to be used for prediction.""" input = input / 255.0 return input[None, :, :] def post_process(prediction: np.ndarray) -> str: """Pre process the data""" classes = [str(i) for i in range(10)] prediction = tf.nn.softmax(prediction, axis=-1) maxindex = np.argmax(prediction.numpy()) return classes[maxindex] ``` {% hint style="info" %} The custom predict function should get the model and the input data as arguments and return the model predictions. ZenML will automatically take care of loading the model into memory and starting the `seldon-core-microservice` that will be responsible for serving the model and running the predict function. {% endhint %} After defining your custom predict function in code, you can use the `seldon_custom_model_deployer_step` to automatically build your function into a Docker image and deploy it as a model server by setting the `predict_function` argument to the path of your `custom_predict` function: ```python from zenml.integrations.seldon.steps import seldon_custom_model_deployer_step from zenml.integrations.seldon.services import SeldonDeploymentConfig from zenml import pipeline @pipeline def seldon_deployment_pipeline(): model = ... seldon_custom_model_deployer_step( model=model, predict_function="", # TODO: path to custom code service_config=SeldonDeploymentConfig( model_name="", # TODO: name of the deployed model replicas=1, implementation="custom", resources=SeldonResourceRequirements( limits={"cpu": "200m", "memory": "250Mi"} ), serviceAccountName="kubernetes-service-account", ), ) ``` #### Advanced Custom Code Deployment with Seldon Core Integration {% hint style="warning" %} Before creating your custom model class, you should take a look at the [custom Python model](https://docs.seldon.io/projects/seldon-core/en/latest/python/python\_wrapping\_docker.html) section of the Seldon Core documentation. {% endhint %} The built-in Seldon Core custom deployment step is a good starting point for deploying your custom models. However, if you want to deploy more than the trained model, you can create your own custom class and a custom step to achieve this. See the [ZenML custom Seldon model class](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-seldon/#zenml.integrations.seldon.custom_deployer.zenml_custom_model.ZenMLCustomModel) as a reference.
ZenML Scarf
================ File: docs/book/component-guide/model-deployers/vllm.md ================ --- description: Deploying your LLM locally with vLLM. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # vLLM [vLLM](https://docs.vllm.ai/en/latest/) is a fast and easy-to-use library for LLM inference and serving. ## When to use it? You should use vLLM Model Deployer: * Deploying Large Language models with state-of-the-art serving throughput creating an OpenAI-compatible API server * Continuous batching of incoming requests * Quantization: GPTQ, AWQ, INT4, INT8, and FP8 * Features such as PagedAttention, Speculative decoding, Chunked pre-fill ## How do you deploy it? The vLLM Model Deployer flavor is provided by the vLLM ZenML integration, so you need to install it on your local machine to be able to deploy your models. You can do this by running the following command: ```bash zenml integration install vllm -y ``` To register the vLLM model deployer with ZenML you need to run the following command: ```bash zenml model-deployer register vllm_deployer --flavor=vllm ``` The ZenML integration will provision a local vLLM deployment server as a daemon process that will continue to run in the background to serve the latest vLLM model. ## How do you use it? If you'd like to see this in action, check out this example of a [deployment pipeline](https://github.com/zenml-io/zenml-projects/blob/79f67ea52c3908b9b33c9a41eef18cb7d72362e8/llm-vllm-deployer/pipelines/deploy_pipeline.py#L25). ### Deploy an LLM The [vllm_model_deployer_step](https://github.com/zenml-io/zenml-projects/blob/79f67ea52c3908b9b33c9a41eef18cb7d72362e8/llm-vllm-deployer/steps/vllm_deployer.py#L32) exposes a `VLLMDeploymentService` that you can use in your pipeline. Here is an example snippet: ```python from zenml import pipeline from typing import Annotated from steps.vllm_deployer import vllm_model_deployer_step from zenml.integrations.vllm.services.vllm_deployment import VLLMDeploymentService @pipeline() def deploy_vllm_pipeline( model: str, timeout: int = 1200, ) -> Annotated[VLLMDeploymentService, "GPT2"]: service = vllm_model_deployer_step( model=model, timeout=timeout, ) return service ``` Here is an [example](https://github.com/zenml-io/zenml-projects/tree/79f67ea52c3908b9b33c9a41eef18cb7d72362e8/llm-vllm-deployer) of running a GPT-2 model using vLLM. #### Configuration Within the `VLLMDeploymentService` you can configure: * `model`: Name or path of the Hugging Face model to use. * `tokenizer`: Name or path of the Hugging Face tokenizer to use. If unspecified, model name or path will be used. * `served_model_name`: The model name(s) used in the API. If not specified, the model name will be the same as the `model` argument. * `trust_remote_code`: Trust remote code from Hugging Face. * `tokenizer_mode`: The tokenizer mode. Allowed choices: ['auto', 'slow', 'mistral'] * `dtype`: Data type for model weights and activations. Allowed choices: ['auto', 'half', 'float16', 'bfloat16', 'float', 'float32'] * `revision`: The specific model version to use. It can be a branch name, a tag name, or a commit id. If unspecified, will use the default version. ================ File: docs/book/component-guide/model-registries/custom.md ================ --- description: Learning how to develop a custom model registry. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a Custom Model Registry {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} {% hint style="warning" %} **Base abstraction in progress!** The Model registry stack component is relatively new in ZenML. While it is fully functional, it can be challenging to cover all the ways ML systems deal with model versioning. This means that the API might change in the future. We will keep this page up-to-date with the latest changes. If you are writing a custom model registry flavor, and you found that the base abstraction is lacking or not flexible enough, please let us know by messaging us on [Slack](https://zenml.io/slack), or by opening an issue on [GitHub](https://github.com/zenml-io/zenml/issues/new/choose) {% endhint %} ### Base Abstraction The `BaseModelRegistry` is the abstract base class that needs to be subclassed in order to create a custom component that can be used to register and retrieve models. As model registries can come in many shapes and forms, the base class exposes a deliberately basic and generic interface: ```python from abc import ABC, abstractmethod from enum import Enum from typing import Any, Dict, List, Optional, Type, cast from pydantic import BaseModel, Field, root_validator from zenml.enums import StackComponentType from zenml.stack import Flavor, StackComponent from zenml.stack.stack_component import StackComponentConfig class BaseModelRegistryConfig(StackComponentConfig): """Base config for model registries.""" class BaseModelRegistry(StackComponent, ABC): """Base class for all ZenML model registries.""" @property def config(self) -> BaseModelRegistryConfig: """Returns the config of the model registry.""" return cast(BaseModelRegistryConfig, self._config) # --------- # Model Registration Methods # --------- @abstractmethod def register_model( self, name: str, description: Optional[str] = None, tags: Optional[Dict[str, str]] = None, ) -> RegisteredModel: """Registers a model in the model registry.""" @abstractmethod def delete_model( self, name: str, ) -> None: """Deletes a registered model from the model registry.""" @abstractmethod def update_model( self, name: str, description: Optional[str] = None, tags: Optional[Dict[str, str]] = None, ) -> RegisteredModel: """Updates a registered model in the model registry.""" @abstractmethod def get_model(self, name: str) -> RegisteredModel: """Gets a registered model from the model registry.""" @abstractmethod def list_models( self, name: Optional[str] = None, tags: Optional[Dict[str, str]] = None, ) -> List[RegisteredModel]: """Lists all registered models in the model registry.""" # --------- # Model Version Methods # --------- @abstractmethod def register_model_version( self, name: str, description: Optional[str] = None, tags: Optional[Dict[str, str]] = None, model_source_uri: Optional[str] = None, version: Optional[str] = None, description: Optional[str] = None, tags: Optional[Dict[str, str]] = None, metadata: Optional[Dict[str, str]] = None, zenml_version: Optional[str] = None, zenml_run_name: Optional[str] = None, zenml_pipeline_name: Optional[str] = None, zenml_step_name: Optional[str] = None, **kwargs: Any, ) -> RegistryModelVersion: """Registers a model version in the model registry.""" @abstractmethod def delete_model_version( self, name: str, version: str, ) -> None: """Deletes a model version from the model registry.""" @abstractmethod def update_model_version( self, name: str, version: str, description: Optional[str] = None, tags: Optional[Dict[str, str]] = None, stage: Optional[ModelVersionStage] = None, ) -> RegistryModelVersion: """Updates a model version in the model registry.""" @abstractmethod def list_model_versions( self, name: Optional[str] = None, model_source_uri: Optional[str] = None, tags: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> List[RegistryModelVersion]: """Lists all model versions for a registered model.""" @abstractmethod def get_model_version(self, name: str, version: str) -> RegistryModelVersion: """Gets a model version for a registered model.""" @abstractmethod def load_model_version( self, name: str, version: str, **kwargs: Any, ) -> Any: """Loads a model version from the model registry.""" @abstractmethod def get_model_uri_artifact_store( self, model_version: RegistryModelVersion, ) -> str: """Gets the URI artifact store for a model version.""" ``` {% hint style="info" %} This is a slimmed-down version of the base implementation which aims to highlight the abstraction layer. To see the full implementation and get the complete docstrings, please check [the source code on GitHub](https://github.com/zenml-io/zenml/blob/main/src/zenml/model\_registries/base\_model\_registry.py) . {% endhint %} ### Build your own custom model registry If you want to create your own custom flavor for a model registry, you can follow the following steps: 1. Learn more about the core concepts for the model registry [here](./model-registries.md#model-registry-concepts-and-terminology). Your custom model registry will be built on top of these concepts so it helps to be aware of them. 2. Create a class that inherits from `BaseModelRegistry` and implements the abstract methods. 3. Create a `ModelRegistryConfig` class that inherits from `BaseModelRegistryConfig` and adds any additional configuration parameters that you need. 4. Bring the implementation and the configuration together by inheriting from the `BaseModelRegistryFlavor` class. Make sure that you give a `name` to the flavor through its abstract property. Once you are done with the implementation, you can register it through the CLI with the following command: ```shell zenml model-registry flavor register ``` {% hint style="warning" %} It is important to draw attention to how and when these base abstractions are coming into play in a ZenML workflow. * The **CustomModelRegistryFlavor** class is imported and utilized upon the creation of the custom flavor through the CLI. * The **CustomModelRegistryConfig** class is imported when someone tries to register/update a stack component with this custom flavor. Most of all, during the registration process of the stack component, the config will be used to validate the values given by the user. As `Config` objects are `pydantic` objects under the hood, you can also add your own custom validators here. * The **CustomModelRegistry** only comes into play when the component is ultimately in use. The design behind this interaction lets us separate the configuration of the flavor from its implementation. This way we can register flavors and components even when the major dependencies behind their implementation are not installed in our local setting (assuming the `CustomModelRegistryFlavor` and the `CustomModelRegistryConfig` are implemented in a different module/path than the actual `CustomModelRegistry`). {% endhint %} For a full implementation example, please check out the [MLFlowModelRegistry](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-mlflow/#zenml.integrations.mlflow.model\_registry.MLFlowModelRegistry)
ZenML Scarf
================ File: docs/book/component-guide/model-registries/mlflow.md ================ --- description: Managing MLFlow logged models and artifacts --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # MLflow Model Registry [MLflow](https://www.mlflow.org/docs/latest/tracking.html) is a popular tool that helps you track experiments, manage models and even deploy them to different environments. ZenML already provides a [MLflow Experiment Tracker](../experiment-trackers/mlflow.md) that you can use to track your experiments, and an [MLflow Model Deployer](../model-deployers/mlflow.md) that you can use to deploy your models locally. The MLflow model registry uses [the MLflow model registry service](https://mlflow.org/docs/latest/model-registry.html) to manage and track ML models and their artifacts and provides a user interface to browse them: ![MLflow Model Registry UI](../../.gitbook/assets/mlflow-ui-models.png) ## When would you want to use it? You can use the MLflow model registry throughout your experimentation, QA, and production phases to manage and track machine learning model versions. It is designed to help teams collaborate on model development and deployment, and keep track of which models are being used in which environments. With the MLflow model registry, you can store and manage models, deploy them to different environments, and track their performance over time. This is particularly useful in the following scenarios: * If you are working on a machine learning project and want to keep track of different model versions as they are developed and deployed. * If you need to deploy machine learning models to different environments and want to keep track of which version is being used in each environment. * If you want to monitor and compare the performance of different model versions over time and make data-driven decisions about which models to use in production. * If you want to simplify the process of deploying models either to a production environment or to a staging environment for testing. ## How do you deploy it? The MLflow Experiment Tracker flavor is provided by the MLflow ZenML integration, so you need to install it on your local machine to be able to register an MLflow model registry component. Note that the MLFlow model registry requires [MLFlow Experiment Tracker](../experiment-trackers/mlflow.md) to be present in the stack. ```shell zenml integration install mlflow -y ``` Once the MLflow integration is installed, you can register an MLflow model registry component in your stack: ```shell zenml model-registry register mlflow_model_registry --flavor=mlflow # Register and set a stack with the new model registry as the active stack zenml stack register custom_stack -r mlflow_model_registry ... --set ``` {% hint style="info" %} The MLFlow model registry will automatically use the same configuration as the MLFlow Experiment Tracker. So if you have a remote MLFlow tracking server configured in your stack, the MLFlow model registry will also use the same configuration. {% endhint %} {% hint style="warning" %} Due to a [critical severity vulnerability](https://github.com/advisories/GHSA-xg73-94fp-g449) found in older versions of MLflow, we recommend using MLflow version 2.2.1 or higher. {% endhint %} ## How do you use it? There are different ways to use the MLflow model registry. You can use it in your ZenML pipelines with the built-in step, or you can use the ZenML CLI to register your model manually or call the model registry API within a custom step in your pipeline. The following sections show you how to use the MLflow model registry in your ZenML pipelines and with the ZenML CLI: ### Register models inside a pipeline ZenML provides a predefined `mlflow_model_deployer_step` that you can use to register a model in the MLflow model registry which you have previously logged to MLflow: ```python from zenml import pipeline from zenml.integrations.mlflow.steps.mlflow_registry import ( mlflow_register_model_step, ) @pipeline def mlflow_registry_training_pipeline(): model = ... mlflow_register_model_step( model=model, name="tensorflow-mnist-model", ) ``` {% hint style="warning" %} The `mlflow_register_model_step` expects that the `model` it receives has already been logged to MLflow in a previous step. E.g., for a scikit-learn model, you would need to have used `mlflow.sklearn.autolog()` or `mlflow.sklearn.log_model(model)` in a previous step. See the [MLflow experiment tracker documentation](../experiment-trackers/mlflow.md) for more information on how to log models to MLflow from your ZenML steps. {% endhint %} #### List of available parameters When using the `mlflow_register_model_step`, you can set a variety of parameters for fine-grained control over which information is logged with your model: * `name`: The name of the model. This is a required parameter. * `version`: version: The version of the model. * `trained_model_name`: Name of the model artifact in MLflow. * `model_source_uri`: The path to the model. If not provided, the model will be fetched from the MLflow tracking server via the `trained_model_name`. * `description`: A description of the model version. * `metadata`: A list of metadata to associate with the model version. {% hint style="info" %} The `model_source_uri` parameter is the path to the model within the MLflow tracking server. If you are using a local MLflow tracking server, the path will be something like `file:///.../mlruns/667102566783201219/3973eabc151c41e6ab98baeb20c5323b/artifacts/model`. If you are using a remote MLflow tracking server, the path will be something like `s3://.../mlruns/667102566783201219/3973eabc151c41e6ab98baeb20c5323b/artifacts/model`. You can find the path of the model in the MLflow UI. Go to the `Artifacts` tab of the run that produced the model and click on the model. The path will be displayed in the URL: Model URI in MLflow UI {% endhint %} ### Register models via the CLI Sometimes adding a `mlflow_registry_training_pipeline` step to your pipeline might not be the best option for you, as it will register a model in the MLflow model registry every time you run the pipeline. If you want to register your models manually, you can use the `zenml model-registry models register-version` CLI command instead: ```shell zenml model-registry models register-version Tensorflow-model \ --description="A new version of the tensorflow model with accuracy 98.88%" \ -v 1 \ --model-uri="file:///.../mlruns/667102566783201219/3973eabc151c41e6ab98baeb20c5323b/artifacts/model" \ -m key1 value1 -m key2 value2 \ --zenml-pipeline-name="mlflow_training_pipeline" \ --zenml-step-name="trainer" ``` ### Deploy a registered model After you have registered a model in the MLflow model registry, you can also easily deploy it as a prediction service. Checkout the [MLflow model deployer documentation](../model-deployers/mlflow.md#deploy-from-model-registry) for more information on how to do that. ### Interact with registered models You can also use the ZenML CLI to interact with registered models and their versions. The `zenml model-registry models list` command will list all registered models in the model registry: ```shell $ zenml model-registry models list ┏━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━┓ ┃ NAME β”‚ DESCRIPTION β”‚ METADATA ┃ ┠────────────────────────┼─────────────┼──────────┨ ┃ tensorflow-mnist-model β”‚ β”‚ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━┛ ``` To list all versions of a specific model, you can use the `zenml model-registry models list-versions REGISTERED_MODEL_NAME` command: ```shell $ zenml model-registry models list-versions tensorflow-mnist-model ┏━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ NAME β”‚ MODEL_VERSION β”‚ VERSION_DESCRIPTION β”‚ METADATA ┃ ┠────────────────────────┼───────────────┼─────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ tensorflow-mnist-model β”‚ 3 β”‚ Run #3 of the mlflow_training_pipeline. β”‚ {'zenml_version': '0.34.0', 'zenml_run_name': 'mlflow_training_pipeline-2023_03_01-08_09_23_672599', 'zenml_pipeline_name': 'mlflow_training_pipeline', ┃ ┃ β”‚ β”‚ β”‚ 'zenml_pipeline_run_uuid': 'a5d4faae-ef70-48f2-9893-6e65d5e51e98', 'epochs': '5', 'optimizer': 'Adam', 'lr': '0.005'} ┃ ┠────────────────────────┼───────────────┼─────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ tensorflow-mnist-model β”‚ 2 β”‚ Run #2 of the mlflow_training_pipeline. β”‚ {'zenml_version': '0.34.0', 'zenml_run_name': 'mlflow_training_pipeline-2023_03_01-08_09_08_467212', 'zenml_pipeline_name': 'mlflow_training_pipeline', ┃ ┃ β”‚ β”‚ β”‚ 'zenml_pipeline_run_uuid': '11858dcf-3e47-4b1a-82c5-6fa25ba4e037', 'epochs': '5', 'optimizer': 'Adam', 'lr': '0.003'} ┃ ┠────────────────────────┼───────────────┼─────────────────────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ tensorflow-mnist-model β”‚ 1 β”‚ Run #1 of the mlflow_training_pipeline. β”‚ {'zenml_version': '0.34.0', 'zenml_run_name': 'mlflow_training_pipeline-2023_03_01-08_08_52_398499', 'zenml_pipeline_name': 'mlflow_training_pipeline', ┃ ┃ β”‚ β”‚ β”‚ 'zenml_pipeline_run_uuid': '29fb22c1-6e0b-4431-9e04-226226506d16', 'epochs': '5', 'optimizer': 'Adam', 'lr': '0.001'} ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` For more details on a specific model version, you can use the `zenml model-registry models get-version REGISTERED_MODEL_NAME -v VERSION` command: ```shell $ zenml model-registry models get-version tensorflow-mnist-model -v 1 ┏━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ MODEL VERSION PROPERTY β”‚ VALUE ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ REGISTERED_MODEL_NAME β”‚ tensorflow-mnist-model ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ VERSION β”‚ 1 ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ VERSION_DESCRIPTION β”‚ Run #1 of the mlflow_training_pipeline. ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT β”‚ 2023-03-01 09:09:06.899000 ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT β”‚ 2023-03-01 09:09:06.899000 ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ METADATA β”‚ {'zenml_version': '0.34.0', 'zenml_run_name': 'mlflow_training_pipeline-2023_03_01-08_08_52_398499', 'zenml_pipeline_name': 'mlflow_training_pipeline', 'zenml_pipeline_run_uuid': '29fb22c1-6e0b-4431-9e04-226226506d16', ┃ ┃ β”‚ 'lr': '0.001', 'epochs': '5', 'optimizer': 'Adam'} ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ MODEL_SOURCE_URI β”‚ file:///Users/safoine-zenml/Library/Application Support/zenml/local_stores/0902a511-117d-4152-a098-b2f1124c4493/mlruns/489728212459131640/293a0d2e71e046999f77a79639f6eac2/artifacts/model ┃ ┠────────────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ STAGE β”‚ None ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` Finally, to delete a registered model or a specific model version, you can use the `zenml model-registry models delete REGISTERED_MODEL_NAME` and `zenml model-registry models delete-version REGISTERED_MODEL_NAME -v VERSION` commands respectively. Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-mlflow/#zenml.integrations.mlflow.model\_registry.MLFlowModelRegistry) to see more about the interface and implementation.
ZenML Scarf
================ File: docs/book/component-guide/model-registries/model-registries.md ================ --- icon: table-rows description: Tracking and managing ML models. --- # Model Registries Model registries are centralized storage solutions for managing and tracking machine learning models across various stages of development and deployment. They help track the different versions and configurations of each model and enable reproducibility. By storing metadata such as version, configuration, and metrics, model registries help streamline the management of trained models. In ZenML, model registries are Stack Components that allow for the easy retrieval, loading, and deployment of trained models. They also provide information on the pipeline in which the model was trained and how to reproduce it. ### Model Registry Concepts and Terminology ZenML provides a unified abstraction for model registries through which it is possible to handle and manage the concepts of model groups, versions, and stages in a consistent manner regardless of the underlying registry tool or platform being used. The following concepts are useful to be aware of for this abstraction: * **RegisteredModel**: A logical grouping of models that can be used to track different versions of a model. It holds information about the model, such as its name, description, and tags, and can be created by the user or automatically created by the model registry when a new model is logged. * **RegistryModelVersion**: A specific version of a model identified by a unique version number or string. It holds information about the model, such as its name, description, tags, and metrics, and a reference to the model artifact logged to the model registry. In ZenML, it also holds a reference to the pipeline name, pipeline run ID, and step name. Each model version is associated with a model registration. * **ModelVersionStage**: A model version stage is a state in that a model version can be. It can be one of the following: `None`, `Staging`, `Production`, `Archived`. The model version stage is used to track the lifecycle of a model version. For example, a model version can be in the `Staging` stage while it is being tested and then moved to the `Production` stage once it is ready for deployment. ### When to use it ZenML provides a built-in mechanism for storing and versioning pipeline artifacts through its mandatory Artifact Store. While this is a powerful way to manage artifacts programmatically, it can be challenging to use without a visual interface. Model registries, on the other hand, offer a visual way to manage and track model metadata, particularly when using a remote orchestrator. They make it easy to retrieve and load models from storage, thanks to built-in integrations. A model registry is an excellent choice for interacting with all the models in your pipeline and managing their state in a centralized way. Using a model registry in your stack is particularly useful if you want to interact with all the logged models in your pipeline, or if you need to manage the state of your models in a centralized way and make it easy to retrieve, load, and deploy these models. ### How model registries fit into the ZenML stack Here is an architecture diagram that shows how a model registry fits into the overall story of a remote stack. ![Model Registries](../../.gitbook/assets/Remote-with-model-registry.png) #### Model Registry Flavors Model Registries are optional stack components provided by integrations: | Model Registry | Flavor | Integration | Notes | | ---------------------------------- | -------- | ----------- | ------------------------------------------ | | [MLflow](mlflow.md) | `mlflow` | `mlflow` | Add MLflow as Model Registry to your stack | | [Custom Implementation](custom.md) | _custom_ | | _custom_ | If you would like to see the available flavors of Model Registry, you can use the command: ```shell zenml model-registry flavor list ``` ### How to use it Model registries are an optional component in the ZenML stack that is tied to the experiment tracker. This means that a model registry can only be used if you are also using an experiment tracker. If you're not using an experiment tracker, you can still store your models in ZenML, but you will need to manually retrieve model artifacts from the artifact store. More information on this can be found in the [documentation on the fetching runs](../../how-to/pipeline-development/build-pipelines/fetching-pipelines.md). To use model registries, you first need to register a model registry in your stack with the same flavor as your experiment tracker. Then, you can register your trained model in the model registry using one of three methods: * (1) using the built-in step in the pipeline. * (2) using the ZenML CLI to register the model from the command line. * (3) registering the model from the model registry UI. Finally, you can use the model registry to retrieve and load your models for deployment or further experimentation.
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/airflow.md ================ --- description: Orchestrating your pipelines to run on Airflow. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Airflow Orchestrator ZenML pipelines can be executed natively as [Airflow](https://airflow.apache.org/) DAGs. This brings together the power of the Airflow orchestration with the ML-specific benefits of ZenML pipelines. Each ZenML step runs in a separate Docker container which is scheduled and started using Airflow. {% hint style="warning" %} If you're going to use a remote deployment of Airflow, you'll also need a [remote ZenML deployment](../../getting-started/deploying-zenml/README.md). {% endhint %} ### When to use it You should use the Airflow orchestrator if * you're looking for a proven production-grade orchestrator. * you're already using Airflow. * you want to run your pipelines locally. * you're willing to deploy and maintain Airflow. ### How to deploy it The Airflow orchestrator can be used to run pipelines locally as well as remotely. In the local case, no additional setup is necessary. There are many options to use a deployed Airflow server: * Use [the ZenML GCP Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) which includes a [Google Cloud Composer](https://cloud.google.com/composer) component. * Use a managed deployment of Airflow such as [Google Cloud Composer](https://cloud.google.com/composer) , [Amazon MWAA](https://aws.amazon.com/managed-workflows-for-apache-airflow/), or [Astronomer](https://www.astronomer.io/). * Deploy Airflow manually. Check out the official [Airflow docs](https://airflow.apache.org/docs/apache-airflow/stable/production-deployment.html) for more information. If you're not using the ZenML GCP Terraform module to deploy Airflow, there are some additional Python packages that you'll need to install in the Python environment of your Airflow server: * `pydantic~=2.7.1`: The Airflow DAG files that ZenML creates for you require Pydantic to parse and validate configuration files. * `apache-airflow-providers-docker` or `apache-airflow-providers-cncf-kubernetes`, depending on which Airflow operator you'll be using to run your pipeline steps. Check out [this section](airflow.md#using-different-airflow-operators) for more information on supported operators. ### How to use it To use the Airflow orchestrator, we need: * The ZenML `airflow` integration installed. If you haven't done so, run ```shell zenml integration install airflow ``` * [Docker](https://docs.docker.com/get-docker/) installed and running. * The orchestrator registered and part of our active stack: ```shell zenml orchestrator register \ --flavor=airflow \ --local=True # set this to `False` if using a remote Airflow deployment # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` {% tabs %} {% tab title="Local" %} Due to dependency conflicts, we need to install the Python packages to start a local Airflow server in a separate Python environment. ```bash # Create a fresh virtual environment in which we install the Airflow server dependencies python -m venv airflow_server_environment source airflow_server_environment/bin/activate # Install the Airflow server dependencies pip install "apache-airflow==2.4.0" "apache-airflow-providers-docker<3.8.0" "pydantic~=2.7.1" ``` Before starting the local Airflow server, we can set a few environment variables to configure it: * `AIRFLOW_HOME`: This variable defines the location where the Airflow server stores its database and configuration files. The default value is `~/airflow`. * `AIRFLOW__CORE__DAGS_FOLDER`: This variable defines the location where the Airflow server looks for DAG files. The default value is `/dags`. * `AIRFLOW__SCHEDULER__DAG_DIR_LIST_INTERVAL`: This variable controls how often the Airflow scheduler checks for new or updated DAGs. By default, the scheduler will check for new DAGs every 30 seconds. This variable can be used to increase or decrease the frequency of the checks, depending on the specific needs of your pipeline. {% hint style="warning" %} When running this on MacOS, you might need to set the `no_proxy` environment variable to prevent crashes due to a bug in Airflow (see [this page](https://github.com/apache/airflow/issues/28487) for more information): ```bash export no_proxy=* ``` {% endhint %} We can now start the local Airflow server by running the following command: ```bash # Switch to the Python environment that has Airflow installed before running this command airflow standalone ``` This command will start up an Airflow server on your local machine. During the startup, it will print a username and password which you can use to log in to the Airflow UI [here](http://0.0.0.0:8080). We can now switch back the Python environment in which ZenML is installed and run a pipeline: ```shell # Switch to the Python environment that has ZenML installed before running this command python file_that_runs_a_zenml_pipeline.py ``` This call will produce a `.zip` file containing a representation of your ZenML pipeline for Airflow. The location of this `.zip` file will be in the logs of the command above. We now need to copy this file to the Airflow DAGs directory, from where the local Airflow server will load it and run your pipeline (It might take a few seconds until the pipeline shows up in the Airflow UI). To figure out the DAGs directory, we can run `airflow config get-value core DAGS_FOLDER` while having our Python environment with the Airflow installation active. To make this process easier, we can configure our ZenML Airflow orchestrator to automatically copy the `.zip` file to this directory for us. To do so, run the following command: ```bash # Switch to the Python environment that has ZenML installed before running this command zenml orchestrator update --dag_output_dir= ``` Now that we've set this up, running a pipeline in Airflow is as simple as just running the Python file: ```shell # Switch to the Python environment that has ZenML installed before running this command python file_that_runs_a_zenml_pipeline.py ``` {% endtab %} {% tab title="Remote" %} When using the Airflow orchestrator with a remote deployment, you'll additionally need: * A remote ZenML server deployed to the cloud. See the [deployment guide](../../getting-started/deploying-zenml/README.md) for more information. * A deployed Airflow server. See the [deployment section](airflow.md#how-to-deploy-it) for more information. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. * A [remote container registry](../container-registries/container-registries.md) as part of your stack. In the remote case, the Airflow orchestrator works differently than other ZenML orchestrators. Executing a python file which runs a pipeline by calling `pipeline.run()` will not actually run the pipeline, but instead will create a `.zip` file containing an Airflow representation of your ZenML pipeline. In one additional step, you need to make sure this zip file ends up in the [DAGs directory](https://airflow.apache.org/docs/apache-airflow/stable/concepts/overview.html#architecture-overview) of your Airflow deployment. {% endtab %} {% endtabs %} {% hint style="info" %} ZenML will build a Docker image called `/zenml:` which includes your code and use it to run your pipeline steps in Airflow. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. {% endhint %} #### Scheduling You can [schedule pipeline runs](../../how-to/pipeline-development/build-pipelines/schedule-a-pipeline.md) on Airflow similarly to other orchestrators. However, note that **Airflow schedules always need to be set in the past**, e.g.,: ```python from datetime import datetime, timedelta from zenml.pipelines import Schedule scheduled_pipeline = fashion_mnist_pipeline.with_options( schedule=Schedule( start_time=datetime.now() - timedelta(hours=1), # start in the past end_time=datetime.now() + timedelta(hours=1), interval_second=timedelta(minutes=15), # run every 15 minutes catchup=False, ) ) scheduled_pipeline() ``` #### Airflow UI Airflow comes with its own UI that you can use to find further details about your pipeline runs, such as the logs of your steps. For local Airflow, you can find the Airflow UI at [http://localhost:8080](http://localhost:8080) by default. {% hint style="info" %} If you cannot see the Airflow UI credentials in the console, you can find the password in `/standalone_admin_password.txt`. `AIRFLOW_HOME` will usually be `~/airflow` unless you've manually configured it with the `AIRFLOW_HOME` environment variable. You can always run `airflow info` to figure out the directory for the active environment. The username will always be `admin`. {% endhint %} #### Additional configuration For additional configuration of the Airflow orchestrator, you can pass `AirflowOrchestratorSettings` when defining or running your pipeline. Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-airflow/#zenml.integrations.airflow.flavors.airflow\_orchestrator\_flavor.AirflowOrchestratorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/README.md) for more information on how to specify settings. #### Enabling CUDA for GPU-backed hardware Note that if you wish to use this orchestrator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration. #### Using different Airflow operators Airflow operators specify how a step in your pipeline gets executed. As ZenML relies on Docker images to run pipeline steps, only operators that support executing a Docker image work in combination with ZenML. Airflow comes with two operators that support this: * the `DockerOperator` runs the Docker images for executing your pipeline steps on the same machine that your Airflow server is running on. For this to work, the server environment needs to have the `apache-airflow-providers-docker` package installed. * the `KubernetesPodOperator` runs the Docker image on a pod in the Kubernetes cluster that the Airflow server is deployed to. For this to work, the server environment needs to have the `apache-airflow-providers-cncf-kubernetes` package installed. You can specify which operator to use and additional arguments to it as follows: ```python from zenml import pipeline, step from zenml.integrations.airflow.flavors.airflow_orchestrator_flavor import AirflowOrchestratorSettings airflow_settings = AirflowOrchestratorSettings( operator="docker", # or "kubernetes_pod" # Dictionary of arguments to pass to the operator __init__ method operator_args={} ) # Using the operator for a single step @step(settings={"orchestrator": airflow_settings}) def my_step(...): # Using the operator for all steps in your pipeline @pipeline(settings={"orchestrator": airflow_settings}) def my_pipeline(...): ``` {% hint style="info" %} If you're using `apache-airflow-providers-cncf-kubernetes>=10.0.0`, the import of the Kubernetes pod operator changed, and you'll need to specify the operator like this: ```python airflow_settings = AirflowOrchestratorSettings( operator="airflow.providers.cncf.kubernetes.operators.pod.KubernetesPodOperator" ) ``` {% endhint %} **Custom operators** If you want to use any other operator to run your steps, you can specify the `operator` in your `AirflowSettings` as a path to the python operator class: ```python from zenml.integrations.airflow.flavors.airflow_orchestrator_flavor import AirflowOrchestratorSettings airflow_settings = AirflowOrchestratorSettings( # This could also be a reference to one of your custom classes. # e.g. `my_module.MyCustomOperatorClass` as long as the class # is importable in your Airflow server environment operator="airflow.providers.docker.operators.docker.DockerOperator", # Dictionary of arguments to pass to the operator __init__ method operator_args={} ) ``` **Custom DAG generator file** To run a pipeline in Airflow, ZenML creates a Zip archive that contains two files: * A JSON configuration file that the orchestrator creates. This file contains all the information required to create the Airflow DAG to run the pipeline. * A Python file that reads this configuration file and actually creates the Airflow DAG. We call this file the `DAG generator` and you can find the implementation [here](https://github.com/zenml-io/zenml/blob/main/src/zenml/integrations/airflow/orchestrators/dag\_generator.py) . If you need more control over how the Airflow DAG is generated, you can provide a custom DAG generator file using the setting `custom_dag_generator`. This setting will need to reference a Python module that can be imported into your active Python environment. It will additionally need to contain the same classes (`DagConfiguration` and `TaskConfiguration`) and constants (`ENV_ZENML_AIRFLOW_RUN_ID`, `ENV_ZENML_LOCAL_STORES_PATH` and `CONFIG_FILENAME`) as the [original module](https://github.com/zenml-io/zenml/blob/main/src/zenml/integrations/airflow/orchestrators/dag\_generator.py) . For this reason, we suggest starting by copying the original and modifying it according to your needs. Check out our docs on how to apply settings to your pipelines [here](../../how-to/pipeline-development/use-configuration-files/README.md). For more information and a full list of configurable attributes of the Airflow orchestrator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-airflow/#zenml.integrations.airflow.orchestrators.airflow_orchestrator.AirflowOrchestrator) .
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/azureml.md ================ --- description: Orchestrating your pipelines to run on AzureML. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # AzureML Orchestrator [AzureML](https://azure.microsoft.com/en-us/products/machine-learning) is a cloud-based orchestration service provided by Microsoft, that enables data scientists, machine learning engineers, and developers to build, train, deploy, and manage machine learning models. It offers a comprehensive and integrated environment that supports the entire machine learning lifecycle, from data preparation and model development to deployment and monitoring. ## When to use it You should use the AzureML orchestrator if: * you're already using Azure. * you're looking for a proven production-grade orchestrator. * you're looking for a UI in which you can track your pipeline runs. * you're looking for a managed solution for running your pipelines. ## How it works The ZenML AzureML orchestrator implementation uses [the Python SDK v2 of AzureML](https://learn.microsoft.com/en-gb/python/api/overview/azure/ai-ml-readme?view=azure-python) to allow our users to build their Machine Learning pipelines. For each ZenML step, it creates an AzureML [CommandComponent](https://learn.microsoft.com/en-us/python/api/azure-ai-ml/azure.ai.ml.entities.commandcomponent?view=azure-python) and brings them together in a pipeline. ## How to deploy it {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including an AzureML orchestrator? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), the [stack registration wizard](../../how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md), or [the ZenML Azure Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} In order to use an AzureML orchestrator, you need to first deploy [ZenML to the cloud](../../getting-started/deploying-zenml/README.md). It would be recommended to deploy ZenML in the same region as you plan on using for AzureML, but it is not necessary to do so. You must ensure that you are [connected to the remote ZenML server](../../how-to/manage-zenml-server/connecting-to-zenml/connect-in-with-your-user-interactive.md) before using this stack component. ## How to use it In order to use the AzureML orchestrator, you need: * The ZenML `azure` integration installed. If you haven't done so, run: ```shell zenml integration install azure ``` * [Docker](https://www.docker.com) installed and running or a remote image builder in your stack. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. * A [remote container registry](../container-registries/container-registries.md) as part of your stack. * An [Azure resource group equipped with an AzureML workspace](https://learn.microsoft.com/en-us/azure/machine-learning/quickstart-create-resources?view=azureml-api-2) to run your pipeline on. There are two ways of authenticating your orchestrator with AzureML: 1. **Default Authentication** simplifies the authentication process while developing your workflows that deploy to Azure by combining credentials used in Azure hosting environments and credentials used in local development. 2. **Service Principal Authentication (recommended)** is using the concept of service principals on Azure to allow you to connect your cloud components with proper authentication. For this method, you will need to [create a service principal on Azure](https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication-on-premises-apps?tabs=azure-portal), assign it the correct permissions and use it to [register a ZenML Azure Service Connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md). ```bash zenml service-connector register --type azure -i zenml orchestrator connect -c ``` ## Docker For each pipeline run, ZenML will build a Docker image called `/zenml:` which includes your code and use it to run your pipeline steps in AzureML. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. ## AzureML UI Each AzureML workspace comes equipped with an Azure Machine Learning studio. Here you can inspect, manage, and debug your pipelines and steps. ![AzureML pipeline example](../../.gitbook/assets/azureml-pipelines.png) Double-clicking any of the steps on this view will open up the overview page for that specific step. Here you can check the configuration of the component and its execution logs. ## Settings The ZenML AzureML orchestrator comes with a dedicated class called `AzureMLOrchestratorSettings` for configuring its settings, and it controls the compute resources used for pipeline execution in AzureML. Currently, it supports three different modes of operation. ### 1. Serverless Compute (Default) - Set `mode` to `serverless`. - Other parameters are ignored. **Example:** ```python from zenml import step, pipeline from zenml.integrations.azure.flavors import AzureMLOrchestratorSettings azureml_settings = AzureMLOrchestratorSettings( mode="serverless" # It's the default behavior ) @step def example_step() -> int: return 3 @pipeline(settings={"orchestrator": azureml_settings}) def pipeline(): example_step() pipeline() ``` ### 2. Compute Instance - Set `mode` to `compute-instance`. - Requires a `compute_name`. - If a compute instance with the same name exists, it uses the existing compute instance and ignores other parameters. (It will throw a warning if the provided configuration does not match the existing instance.) - If a compute instance with the same name doesn't exist, it creates a new compute instance with the `compute_name`. For this process, you can specify `size` and `idle_type_before_shutdown_minutes`. **Example:** ```python from zenml import step, pipeline from zenml.integrations.azure.flavors import AzureMLOrchestratorSettings azureml_settings = AzureMLOrchestratorSettings( mode="compute-instance", compute_name="my-gpu-instance", # Will fetch or create this instance size="Standard_NC6s_v3", # Using a NVIDIA Tesla V100 GPU idle_time_before_shutdown_minutes=20, ) @step def example_step() -> int: return 3 @pipeline(settings={"orchestrator": azureml_settings}) def pipeline(): example_step() pipeline() ``` ### 3. Compute Cluster - Set `mode` to `compute-cluster`. - Requires a `compute_name`. - If a compute cluster with the same name exists, it uses existing cluster, ignores other parameters. (It will throw a warning if the provided - configuration does not match the existing cluster.) - If a compute cluster with the same name doesn't exist, it creates a new compute cluster. Additional parameters can be used for configuring this process. **Example:** ```python from zenml import step, pipeline from zenml.integrations.azure.flavors import AzureMLOrchestratorSettings azureml_settings = AzureMLOrchestratorSettings( mode="compute-cluster", compute_name="my-gpu-cluster", # Will fetch or create this instance size="Standard_NC6s_v3", # Using a NVIDIA Tesla V100 GPU tier="Dedicated", # Can be set to either "Dedicated" or "LowPriority" min_instances=2, max_instances=10, idle_time_before_scaledown_down=60, ) @step def example_step() -> int: return 3 @pipeline(settings={"orchestrator": azureml_settings}) def pipeline(): example_step() pipeline() ``` {% hint style="info" %} In order to learn more about the supported sizes for compute instances and clusters, you can check [the AzureML documentation](https://learn.microsoft.com/en-us/azure/machine-learning/concept-compute-target?view=azureml-api-2#supported-vm-series-and-sizes). {% endhint %} ### Run pipelines on a schedule The AzureML orchestrator supports running pipelines on a schedule using its [JobSchedules](https://learn.microsoft.com/en-us/azure/machine-learning/how-to-schedule-pipeline-job?view=azureml-api-2&tabs=python). Both cron expression and intervals are supported. ```python from zenml.config.schedule import Schedule # Run a pipeline every 5th minute pipeline.run(schedule=Schedule(cron_expression="*/5 * * * *")) ``` Once you run the pipeline with a schedule, you can find the schedule and the corresponding run under the `All Schedules` tab `Jobs` in the jobs page on AzureML. {% hint style="warning" %} Note that ZenML only gets involved to schedule a run, but maintaining the lifecycle of the schedule is the responsibility of the user. That means, if you want to cancel a schedule that you created on AzureML, you will have to do it through the Azure UI. {% endhint %}
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/custom.md ================ --- description: Learning how to develop a custom orchestrator. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a custom orchestrator {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} ### Base Implementation ZenML aims to enable orchestration with any orchestration tool. This is where the `BaseOrchestrator` comes into play. It abstracts away many of the ZenML-specific details from the actual implementation and exposes a simplified interface: ```python from abc import ABC, abstractmethod from typing import Any, Dict, Type from zenml.models import PipelineDeploymentResponseModel from zenml.enums import StackComponentType from zenml.stack import StackComponent, StackComponentConfig, Stack, Flavor class BaseOrchestratorConfig(StackComponentConfig): """Base class for all ZenML orchestrator configurations.""" class BaseOrchestrator(StackComponent, ABC): """Base class for all ZenML orchestrators""" @abstractmethod def prepare_or_run_pipeline( self, deployment: PipelineDeploymentResponseModel, stack: Stack, environment: Dict[str, str], ) -> Any: """Prepares and runs the pipeline outright or returns an intermediate pipeline representation that gets deployed. """ @abstractmethod def get_orchestrator_run_id(self) -> str: """Returns the run id of the active orchestrator run. Important: This needs to be a unique ID and return the same value for all steps of a pipeline run. Returns: The orchestrator run id. """ class BaseOrchestratorFlavor(Flavor): """Base orchestrator for all ZenML orchestrator flavors.""" @property @abstractmethod def name(self): """Returns the name of the flavor.""" @property def type(self) -> StackComponentType: """Returns the flavor type.""" return StackComponentType.ORCHESTRATOR @property def config_class(self) -> Type[BaseOrchestratorConfig]: """Config class for the base orchestrator flavor.""" return BaseOrchestratorConfig @property @abstractmethod def implementation_class(self) -> Type["BaseOrchestrator"]: """Implementation class for this flavor.""" ``` {% hint style="info" %} This is a slimmed-down version of the base implementation which aims to highlight the abstraction layer. In order to see the full implementation and get the complete docstrings, please check [the source code on GitHub](https://github.com/zenml-io/zenml/blob/main/src/zenml/orchestrators/base\_orchestrator.py) . {% endhint %} ### Build your own custom orchestrator If you want to create your own custom flavor for an orchestrator, you can follow the following steps: 1. Create a class that inherits from the `BaseOrchestrator` class and implement the abstract `prepare_or_run_pipeline(...)` and `get_orchestrator_run_id()` methods. 2. If you need to provide any configuration, create a class that inherits from the `BaseOrchestratorConfig` class and add your configuration parameters. 3. Bring both the implementation and the configuration together by inheriting from the `BaseOrchestratorFlavor` class. Make sure that you give a `name` to the flavor through its abstract property. Once you are done with the implementation, you can register it through the CLI. Please ensure you **point to the flavor class via dot notation**: ```shell zenml orchestrator flavor register ``` For example, if your flavor class `MyOrchestratorFlavor` is defined in `flavors/my_flavor.py`, you'd register it by doing: ```shell zenml orchestrator flavor register flavors.my_flavor.MyOrchestratorFlavor ``` {% hint style="warning" %} ZenML resolves the flavor class by taking the path where you initialized zenml (via `zenml init`) as the starting point of resolution. Therefore, please ensure you follow [the best practice](../../how-to/infrastructure-deployment/infrastructure-as-code/best-practices.md) of initializing zenml at the root of your repository. If ZenML does not find an initialized ZenML repository in any parent directory, it will default to the current working directory, but usually, it's better to not have to rely on this mechanism and initialize zenml at the root. {% endhint %} Afterward, you should see the new flavor in the list of available flavors: ```shell zenml orchestrator flavor list ``` {% hint style="warning" %} It is important to draw attention to when and how these base abstractions are coming into play in a ZenML workflow. * The **CustomOrchestratorFlavor** class is imported and utilized upon the creation of the custom flavor through the CLI. * The **CustomOrchestratorConfig** class is imported when someone tries to register/update a stack component with this custom flavor. Especially, during the registration process of the stack component, the config will be used to validate the values given by the user. As `Config` object are inherently `pydantic` objects, you can also add your own custom validators here. * The **CustomOrchestrator** only comes into play when the component is ultimately in use. The design behind this interaction lets us separate the configuration of the flavor from its implementation. This way we can register flavors and components even when the major dependencies behind their implementation are not installed in our local setting (assuming the `CustomOrchestratorFlavor` and the `CustomOrchestratorConfig` are implemented in a different module/path than the actual `CustomOrchestrator`). {% endhint %} ## Implementation guide 1. **Create your orchestrator class:** This class should either inherit from `BaseOrchestrator`, or more commonly from `ContainerizedOrchestrator`. If your orchestrator uses container images to run code, you should inherit from `ContainerizedOrchestrator` which handles building all Docker images for the pipeline to be executed. If your orchestator does not use container images, you'll be responsible that the execution environment contains all the necessary requirements and code files to run the pipeline. 2. **Implement the `prepare_or_run_pipeline(...)` method:** This method is responsible for running or scheduling the pipeline. In most cases, this means converting the pipeline into a format that your orchestration tool understands and running it. To do so, you should: * Loop over all steps of the pipeline and configure your orchestration tool to run the correct command and arguments in the correct Docker image * Make sure the passed environment variables are set when the container is run * Make sure the containers are running in the correct order Check out the [code sample](custom.md#code-sample) below for more details on how to fetch the Docker image, command, arguments and step order. 3. **Implement the `get_orchestrator_run_id()` method:** This must return a ID that is different for each pipeline run, but identical if called from within Docker containers running different steps of the same pipeline run. If your orchestrator is based on an external tool like Kubeflow or Airflow, it is usually best to use an unique ID provided by this tool. {% hint style="info" %} To see a full end-to-end worked example of a custom orchestrator, [see here](https://github.com/zenml-io/zenml-plugins/tree/main/how\_to\_custom\_orchestrator). {% endhint %} ### Optional features There are some additional optional features that your orchestrator can implement: * **Running pipelines on a schedule**: if your orchestrator supports running pipelines on a schedule, make sure to handle `deployment.schedule` if it exists. If your orchestrator does not support schedules, you should either log a warning and or even raise an exception in case the user tries to schedule a pipeline. * **Specifying hardware resources**: If your orchestrator supports setting resources like CPUs, GPUs or memory for the pipeline or specific steps, make sure to handle the values defined in `step.config.resource_settings`. See the code sample below for additional helper methods to check whether any resources are required from your orchestrator. ### Code sample ```python from typing import Dict from zenml.entrypoints import StepEntrypointConfiguration from zenml.models import PipelineDeploymentResponseModel from zenml.orchestrators import ContainerizedOrchestrator from zenml.stack import Stack class MyOrchestrator(ContainerizedOrchestrator): def get_orchestrator_run_id(self) -> str: # Return an ID that is different each time a pipeline is run, but the # same for all steps being executed as part of the same pipeline run. # If you're using some external orchestration tool like Kubeflow, you # can usually use the run ID of that tool here. ... def prepare_or_run_pipeline( self, deployment: "PipelineDeploymentResponseModel", stack: "Stack", environment: Dict[str, str], ) -> None: # If your orchestrator supports scheduling, you should handle the schedule # configured by the user. Otherwise you might raise an exception or log a warning # that the orchestrator doesn't support scheduling if deployment.schedule: ... for step_name, step in deployment.step_configurations.items(): image = self.get_image(deployment=deployment, step_name=step_name) command = StepEntrypointConfiguration.get_entrypoint_command() arguments = StepEntrypointConfiguration.get_entrypoint_arguments( step_name=step_name, deployment_id=deployment.id ) # Your orchestration tool should run this command and arguments # in the Docker image fetched above. Additionally, the container which # is running the command must contain the environment variables specified # in the `environment` dictionary. # If your orchestrator supports parallel execution of steps, make sure # each step only runs after all its upstream steps finished upstream_steps = step.spec.upstream_steps # You can get the settings your orchestrator like so. # The settings are the "dynamic" part of your orchestrators config, # optionally defined when you register your orchestrator but can be # overridden at runtime. # In contrast, the "static" part of your orchestrators config is # always defined when you register the orchestrator and can be # accessed via `self.config`. step_settings = cast( MyOrchestratorSettings, self.get_settings(step) ) # If your orchestrator supports setting resources like CPUs, GPUs or # memory for the pipeline or specific steps, you can find out whether # specific resources were specified for this step: if self.requires_resources_in_orchestration_environment(step): resources = step.config.resource_settings ``` {% hint style="info" %} To see a full end-to-end worked example of a custom orchestrator, [see here](https://github.com/zenml-io/zenml-plugins/tree/main/how\_to\_custom\_orchestrator). {% endhint %} ### Enabling CUDA for GPU-backed hardware Note that if you wish to use your custom orchestrator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/databricks.md ================ --- description: Orchestrating your pipelines to run on Databricks. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Databricks Orchestrator [Databricks](https://www.databricks.com/) is a unified data analytics platform that combines the best of data warehouses and data lakes to offer an integrated solution for big data processing and machine learning. It provides a collaborative environment for data scientists, data engineers, and business analysts to work together on data projects. Databricks offers optimized performance and scalability for big data workloads. The Databricks orchestrator is an orchestrator flavor provided by the ZenML databricks integration that allows you to run your pipelines on Databricks. This integration enables you to leverage Databricks' powerful distributed computing capabilities and optimized environment for your ML pipelines within the ZenML framework. {% hint style="warning" %} The following features are currently in Alpha and may be subject to change. We recommend using them in a controlled environment and providing feedback to the ZenML team. {% endhint %} ### When to use it You should use the Databricks orchestrator if: * you're already using Databricks for your data and ML workloads. * you want to leverage Databricks' powerful distributed computing capabilities for your ML pipelines. * you're looking for a managed solution that integrates well with other Databricks services. * you want to take advantage of Databricks' optimization for big data processing and machine learning. ### Prerequisites You will need to do the following to start using the Databricks orchestrator: * An Active Databricks workspace, depends on the cloud provider you are using, you can find more information on how to create a workspace: * [AWS](https://docs.databricks.com/en/getting-started/onboarding-account.html) * [Azure](https://learn.microsoft.com/en-us/azure/databricks/getting-started/#--create-an-azure-databricks-workspace) * [GCP](https://docs.gcp.databricks.com/en/getting-started/index.html) * Active Databricks account or service account with sufficient permission to create and run jobs ## How it works ![Databricks How It works Diagram](../../.gitbook/assets/Databricks_How_It_works.png) The Databricks orchestrator in ZenML leverages the concept of Wheel Packages. When you run a pipeline with the Databricks orchestrator, ZenML creates a Python wheel package from your project. This wheel package contains all the necessary code and dependencies for your pipeline. Once the wheel package is created, ZenML uploads it to Databricks. ZenML leverage Databricks SDK to create a job definition, This job definition includes information about the pipeline steps and ensures that each step is executed only after its upstream steps have successfully completed. The Databricks job is also configured with the necessary cluster settings to run. This includes specifying the version of Spark to use, the number of workers, the node type, and other configuration options. When the Databricks job is executed, it retrieves the wheel package from Databricks and runs the pipeline using the specified cluster configuration. The job ensures that the steps are executed in the correct order based on their dependencies. Once the job is completed, ZenML retrieves the logs and status of the job and updates the pipeline run accordingly. This allows you to monitor the progress of your pipeline and view the logs of each step. ### How to use it To use the Databricks orchestrator, you first need to register it and add it to your stack. Before registering the orchestrator, you need to install the Databricks integration by running the following command: ```shell zenml integration install databricks ``` This command will install the necessary dependencies, including the `databricks-sdk` package, which is required for authentication with Databricks. Once the integration is installed, you can proceed with registering the orchestrator and configuring the necessary authentication details. ```shell zenml integration install databricks ``` Then, we can register the orchestrator and use it in our active stack: ```shell zenml orchestrator register databricks_orchestrator --flavor=databricks --host="https://xxxxx.x.azuredatabricks.net" --client_id={{databricks.client_id}} --client_secret={{databricks.client_secret}} ``` {% hint style="info" %} We recommend creating a Databricks service account with the necessary permissions to create and run jobs. You can find more information on how to create a service account [here](https://docs.databricks.com/dev-tools/api/latest/authentication.html). You can generate a client_id and client_secret for the service account and use them to authenticate with Databricks. ![Databricks Service Account Permession](../../.gitbook/assets/DatabricksPermessions.png) {% endhint %} ```shell # Add the orchestrator to your stack zenml stack register databricks_stack -o databricks_orchestrator ... --set ``` You can now run any ZenML pipeline using the Databricks orchestrator: ```shell python run.py ``` ### Databricks UI Databricks comes with its own UI that you can use to find further details about your pipeline runs, such as the logs of your steps. ![Databricks UI](../../.gitbook/assets/DatabricksUI.png) For any runs executed on Databricks, you can get the URL to the Databricks UI in Python using the following code snippet: ```python from zenml.client import Client pipeline_run = Client().get_pipeline_run("") orchestrator_url = pipeline_run.run_metadata["orchestrator_url"].value ``` ![Databricks Run UI](../../.gitbook/assets/DatabricksRunUI.png) ### Run pipelines on a schedule The Databricks Pipelines orchestrator supports running pipelines on a schedule using its [native scheduling capability](https://docs.databricks.com/en/workflows/jobs/schedule-jobs.html). **How to schedule a pipeline** ```python from zenml.config.schedule import Schedule # Run a pipeline every 5th minute pipeline_instance.run( schedule=Schedule( cron_expression="*/5 * * * *" ) ) ``` {% hint style="warning" %} The Databricks orchestrator only supports the `cron_expression`, in the `Schedule` object, and will ignore all other parameters supplied to define the schedule. {% endhint %} {% hint style="warning" %} The Databricks orchestrator requires Java Timezone IDs to be used in the `cron_expression`. You can find a list of supported timezones [here](https://docs.oracle.com/middleware/1221/wcs/tag-ref/MISC/TimeZones.html), the timezone ID must be set in the settings of the orchestrator (see below for more information how to set settings for the orchestrator). {% endhint %} **How to delete a scheduled pipeline** Note that ZenML only gets involved to schedule a run, but maintaining the lifecycle of the schedule is the responsibility of the user. In order to cancel a scheduled Databricks pipeline, you need to manually delete the schedule in Databricks (via the UI or the CLI). ### Additional configuration For additional configuration of the Databricks orchestrator, you can pass `DatabricksOrchestratorSettings` which allows you to change the Spark version, number of workers, node type, autoscale settings, Spark configuration, Spark environment variables, and schedule timezone. ```python from zenml.integrations.databricks.flavors.databricks_orchestrator_flavor import DatabricksOrchestratorSettings databricks_settings = DatabricksOrchestratorSettings( spark_version="15.3.x-scala2.12", num_workers="3", node_type_id="Standard_D4s_v5", policy_id=POLICY_ID, autoscale=(2, 3), spark_conf={}, spark_env_vars={}, schedule_timezone="America/Los_Angeles" or "PST" # You can get the timezone ID from here: https://docs.oracle.com/middleware/1221/wcs/tag-ref/MISC/TimeZones.html ) ``` These settings can then be specified on either pipeline-level or step-level: ```python # Either specify on pipeline-level @pipeline( settings={ "orchestrator": databricks_settings, } ) def my_pipeline(): ... ``` We can also enable GPU support for the Databricks orchestrator changing the `spark_version` and `node_type_id` to a GPU-enabled version and node type: ```python from zenml.integrations.databricks.flavors.databricks_orchestrator_flavor import DatabricksOrchestratorSettings databricks_settings = DatabricksOrchestratorSettings( spark_version="15.3.x-gpu-ml-scala2.12", node_type_id="Standard_NC24ads_A100_v4", policy_id=POLICY_ID, autoscale=(1, 2), ) ``` With these settings, the orchestrator will use a GPU-enabled Spark version and a GPU-enabled node type to run the pipeline on Databricks, next section will show how to enable CUDA for the GPU to give its full acceleration for your pipeline. #### Enabling CUDA for GPU-backed hardware Note that if you wish to use this orchestrator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-databricks/#zenml.integrations.databricks.flavors.databricks\_orchestrator\_flavor.DatabricksOrchestratorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings. For more information and a full list of configurable attributes of the Databricks orchestrator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-databricks/#zenml.integrations.databricks.orchestrators.databricks\_orchestrator.DatabricksOrchestrator) . ================ File: docs/book/component-guide/orchestrators/hyperai.md ================ --- description: Orchestrating your pipelines to run on HyperAI.ai instances. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # HyperAI Orchestrator [HyperAI](https://www.hyperai.ai) is a cutting-edge cloud compute platform designed to make AI accessible for everyone. The HyperAI orchestrator is an [orchestrator](./orchestrators.md) flavor that allows you to easily deploy your pipelines on HyperAI instances. {% hint style="warning" %} This component is only meant to be used within the context of a [remote ZenML deployment scenario](../../getting-started/deploying-zenml/README.md). Usage with a local ZenML deployment may lead to unexpected behavior! {% endhint %} ### When to use it You should use the HyperAI orchestrator if: * you're looking for a managed solution for running your pipelines. * you're a HyperAI customer. ### Prerequisites You will need to do the following to start using the HyperAI orchestrator: * Have a running HyperAI instance. It must be accessible from the internet (or at least from the IP addresses of your ZenML users) and allow SSH key based access (passwords are not supported). * Ensure that a recent version of Docker is installed. This version must include Docker Compose, meaning that the command `docker compose` works. * Ensure that the appropriate [NVIDIA Driver](https://www.nvidia.com/en-us/drivers/unix/) is installed on the HyperAI instance (if not already installed by the HyperAI team). * Ensure that the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html) is installed and configured on the HyperAI instance. Note that it is possible to omit installing the NVIDIA Driver and NVIDIA Container Toolkit. However, you will then be unable to use the GPU from within your ZenML pipeline. Additionally, you will then need to disable GPU access within the container when configuring the Orchestrator component, or the pipeline will not start correctly. ## How it works The HyperAI orchestrator works with Docker Compose, which can be used to construct machine learning pipelines. Under the hood, it creates a Docker Compose file which it then deploys and executes on the configured HyperAI instance. For each ZenML pipeline step, it creates a service in this file. It uses the `service_completed_successfully` condition to ensure that pipeline steps will only run if their connected upstream steps have successfully finished. If configured for it, the HyperAI orchestrator will connect the HyperAI instance to the stack's container registry to ensure a smooth transfer of Docker images. ### Scheduled pipelines [Scheduled pipelines](../../how-to/pipeline-development/build-pipelines/schedule-a-pipeline.md) are supported by the HyperAI orchestrator. Currently, the HyperAI orchestrator supports the following inputs to `Schedule`: * Cron expressions via `cron_expression`. When pipeline runs are scheduled, they are added as a crontab entry on the HyperAI instance. Use this when you want pipelines to run in intervals. Using cron expressions assumes that `crontab` is available on your instance and that its daemon is running. * Scheduled runs via `run_once_start_time`. When pipeline runs are scheduled this way, they are added as an `at` entry on the HyperAI instance. Use this when you want pipelines to run just once and at a specified time. This assumes that `at` is available on your instance. ### How to deploy it To use the HyperAI orchestrator, you must configure a HyperAI Service Connector in ZenML and link it to the HyperAI orchestrator component. The service connector contains credentials with which ZenML connects to the HyperAI instance. Additionally, the HyperAI orchestrator must be used in a stack that contains a container registry and an image builder. ### How to use it To use the HyperAI orchestrator, we must configure a HyperAI Service Connector first using one of its supported authentication methods. For example, for authentication with an RSA-based key, create the service connector as follows: ```shell zenml service-connector register --type=hyperai --auth-method=rsa-key --base64_ssh_key= --hostnames=,,.., --username= ``` Hostnames are either DNS resolvable names or IP addresses. For example, if you have two servers - one at `1.2.3.4` and another at `4.3.2.1`, you could provide them as `--hostnames=1.2.3.4,4.3.2.1`. Optionally, it is possible to provide a passphrase for the key (`--ssh_passphrase`). Following registering the service connector, we can register the orchestrator and use it in our active stack: ```shell zenml orchestrator register --flavor=hyperai # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` You can now run any ZenML pipeline using the HyperAI orchestrator: ```shell python file_that_runs_a_zenml_pipeline.py ``` #### Enabling CUDA for GPU-backed hardware Note that if you wish to use this orchestrator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/kubeflow.md ================ --- description: Orchestrating your pipelines to run on Kubeflow. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Kubeflow Orchestrator The Kubeflow orchestrator is an [orchestrator](./orchestrators.md) flavor provided by the ZenML `kubeflow` integration that uses [Kubeflow Pipelines](https://www.kubeflow.org/docs/components/pipelines/overview/) to run your pipelines. {% hint style="warning" %} This component is only meant to be used within the context of a [remote ZenML deployment scenario](../../getting-started/deploying-zenml/README.md). Usage with a local ZenML deployment may lead to unexpected behavior! {% endhint %} ### When to use it You should use the Kubeflow orchestrator if: * you're looking for a proven production-grade orchestrator. * you're looking for a UI in which you can track your pipeline runs. * you're already using Kubernetes or are not afraid of setting up and maintaining a Kubernetes cluster. * you're willing to deploy and maintain Kubeflow Pipelines on your cluster. ### How to deploy it To run ZenML pipelines on Kubeflow, you'll need to set up a Kubernetes cluster and deploy Kubeflow Pipelines on it. This can be done in a variety of ways, depending on whether you want to use a cloud provider or your own infrastructure: {% tabs %} {% tab title="AWS" %} * Have an existing AWS [EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html) set up. * Make sure you have the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) set up. * Download and [install](https://kubernetes.io/docs/tasks/tools/) `kubectl` and [configure](https://aws.amazon.com/premiumsupport/knowledge-center/eks-cluster-connection/) it to talk to your EKS cluster using the following command: ```powershell aws eks --region REGION update-kubeconfig --name CLUSTER_NAME ``` * [Install](https://www.kubeflow.org/docs/components/pipelines/operator-guides/installation/#deploying-kubeflow-pipelines) Kubeflow Pipelines onto your cluster. * ( optional) [set up an AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md) to grant ZenML Stack Components easy and secure access to the remote EKS cluster. {% endtab %} {% tab title="GCP" %} * Have an existing GCP [GKE cluster](https://cloud.google.com/kubernetes-engine/docs/quickstart) set up. * Make sure you have the [Google Cloud CLI](https://cloud.google.com/sdk/docs/install-sdk) set up first. * Download and [install](https://kubernetes.io/docs/tasks/tools/) `kubectl` and [configure](https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl) it to talk to your GKE cluster using the following command: ```powershell gcloud container clusters get-credentials CLUSTER_NAME ``` * [Install](https://www.kubeflow.org/docs/distributions/gke/deploy/overview/) Kubeflow Pipelines onto your cluster. * ( optional) [set up a GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) to grant ZenML Stack Components easy and secure access to the remote GKE cluster. {% endtab %} {% tab title="Azure" %} * Have an existing [AKS cluster](https://azure.microsoft.com/en-in/services/kubernetes-service/#documentation) set up. * Make sure you have the [`az` CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli) set up first. * Download and [install](https://kubernetes.io/docs/tasks/tools/) `kubectl` and ensure that it talks to your AKS cluster using the following command: ```powershell az aks get-credentials --resource-group RESOURCE_GROUP --name CLUSTER_NAME ``` * [Install](https://www.kubeflow.org/docs/components/pipelines/operator-guides/installation/#deploying-kubeflow-pipelines) Kubeflow Pipelines onto your cluster. {% hint style="info" %} Since Kubernetes v1.19, AKS has shifted to [`containerd`](https://docs.microsoft.com/en-us/azure/aks/cluster-configuration#container-settings). However, the workflow controller installed with the Kubeflow installation has `Docker` set as the default runtime. In order to make your pipelines work, you have to change the value to one of the options listed [here](https://argoproj.github.io/argo-workflows/workflow-executors/#workflow-executors), preferably `k8sapi`. This change has to be made by editing the `containerRuntimeExecutor` property of the `ConfigMap` corresponding to the workflow controller. Run the following commands to first know what config map to change and then to edit it to reflect your new value: ``` kubectl get configmap -n kubeflow kubectl edit configmap CONFIGMAP_NAME -n kubeflow # This opens up an editor that can be used to make the change. ``` {% endhint %} {% endtab %} {% tab title="Other Kubernetes" %} * Have an existing Kubernetes cluster set up. * Download and [install](https://kubernetes.io/docs/tasks/tools/) `kubectl` and configure it to talk to your Kubernetes cluster. * [Install](https://www.kubeflow.org/docs/components/pipelines/operator-guides/installation/#deploying-kubeflow-pipelines) Kubeflow Pipelines onto your cluster. * ( optional) [set up a Kubernetes Service Connector](../../how-to/infrastructure-deployment/auth-management/kubernetes-service-connector.md) to grant ZenML Stack Components easy and secure access to the remote Kubernetes cluster. This is especially useful if your Kubernetes cluster is remotely accessible, as this enables other ZenML users to use it to run pipelines without needing to configure and set up `kubectl` on their local machines. {% endtab %} {% endtabs %} {% hint style="info" %} If one or more of the deployments are not in the `Running` state, try increasing the number of nodes in your cluster. {% endhint %} {% hint style="warning" %} If you're installing Kubeflow Pipelines manually, make sure the Kubernetes service is called exactly `ml-pipeline`. This is a requirement for ZenML to connect to your Kubeflow Pipelines deployment. {% endhint %} ### How to use it To use the Kubeflow orchestrator, we need: * A Kubernetes cluster with Kubeflow pipelines installed. See the [deployment section](kubeflow.md#how-to-deploy-it) for more information. * A ZenML server deployed remotely where it can be accessed from the Kubernetes cluster. See the [deployment guide](../../getting-started/deploying-zenml/README.md) for more information. * The ZenML `kubeflow` integration installed. If you haven't done so, run ```shell zenml integration install kubeflow ``` * [Docker](https://www.docker.com) installed and running (unless you are using a remote [Image Builder](../image-builders/image-builders.md) in your ZenML stack). * [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) installed (optional, see below) {% hint style="info" %} If you are using a single-tenant Kubeflow installed in a Kubernetes cluster managed by a cloud provider like AWS, GCP or Azure, it is recommended that you set up [a Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) and use it to connect ZenML Stack Components to the remote Kubernetes cluster. This guarantees that your Stack is fully portable on other environments and your pipelines are fully reproducible. {% endhint %} * The name of your Kubernetes context which points to your remote cluster. Run `kubectl config get-contexts` to see a list of available contexts. **NOTE**: this is no longer required if you are using [a Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) to connect your Kubeflow Orchestrator Stack Component to the remote Kubernetes cluster. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. * A [remote container registry](../container-registries/container-registries.md) as part of your stack. We can then register the orchestrator and use it in our active stack. This can be done in two ways: 1. If you have [a Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) configured to access the remote Kubernetes cluster, you no longer need to set the `kubernetes_context` attribute to a local `kubectl` context. In fact, you don't need the local Kubernetes CLI at all. You can [connect the stack component to the Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md#connect-stack-components-to-resources) instead: ```shell # List all available Kubernetes clusters that can be accessed by service connectors zenml service-connector list-resources --resource-type kubernetes-cluster -e # Register the Kubeflow orchestrator and connect it to the remote Kubernetes cluster zenml orchestrator register --flavor kubeflow --connector --resource-id # Register a new stack with the orchestrator zenml stack register -o -a -c ... # Add other stack components as needed ``` The following example demonstrates how to register the orchestrator and connect it to a remote Kubernetes cluster using a Service Connector: ```shell $ zenml service-connector list-resources --resource-type kubernetes-cluster -e The following 'kubernetes-cluster' resources can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ e33c9fac-5daa-48b2-87bb-0187d3782cde β”‚ aws-iam-multi-eu β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ kubeflowmultitenant ┃ ┃ β”‚ β”‚ β”‚ β”‚ zenbox ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ ed528d5a-d6cb-4fc4-bc52-c3d2d01643e5 β”‚ aws-iam-multi-us β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ zenhacks-cluster ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ 1c54b32a-4889-4417-abbd-42d3ace3d03a β”‚ gcp-sa-multi β”‚ πŸ”΅ gcp β”‚ πŸŒ€ kubernetes-cluster β”‚ zenml-test-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┛ $ zenml orchestrator register aws-kubeflow --flavor kubeflow --connector aws-iam-multi-eu --resource-id zenhacks-cluster Successfully registered orchestrator `aws-kubeflow`. Successfully connected orchestrator `aws-kubeflow` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼──────────────────┼────────────────┼───────────────────────┼──────────────────┨ ┃ ed528d5a-d6cb-4fc4-bc52-c3d2d01643e5 β”‚ aws-iam-multi-us β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ zenhacks-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┛ # Create a new stack with the orchestrator $ zenml stack register --set aws-kubeflow -o aws-kubeflow -a aws-s3 -c aws-ecr Stack 'aws-kubeflow' successfully registered! Stack Configuration ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┓ ┃ COMPONENT_TYPE β”‚ COMPONENT_NAME ┃ ┠────────────────────┼─────────────────┨ ┃ ARTIFACT_STORE β”‚ aws-s3 ┃ ┠────────────────────┼─────────────────┨ ┃ ORCHESTRATOR β”‚ aws-kubeflow ┃ ┠────────────────────┼─────────────────┨ ┃ CONTAINER_REGISTRY β”‚ aws-ecr ┃ ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┛ 'aws-kubeflow' stack No labels are set for this stack. Stack 'aws-kubeflow' with id 'dab28f94-36ab-467a-863e-8718bbc1f060' is owned by user user. Active global stack set to:'aws-kubeflow' ``` 2. if you don't have a Service Connector on hand and you don't want to [register one](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md#register-service-connectors), the local Kubernetes `kubectl` client needs to be configured with a configuration context pointing to the remote cluster. The `kubernetes_context` must also be configured with the value of that context: ```shell zenml orchestrator register \ --flavor=kubeflow \ --kubernetes_context= # Register a new stack with the orchestrator zenml stack register -o -a -c ... # Add other stack components as needed ``` {% endtab %} {% endtabs %} {% hint style="info" %} ZenML will build a Docker image called `/zenml:` which includes all required software dependencies and use it to run your pipeline steps in Kubeflow. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. {% endhint %} You can now run any ZenML pipeline using the Kubeflow orchestrator: ```shell python file_that_runs_a_zenml_pipeline.py ``` #### Kubeflow UI Kubeflow comes with its own UI that you can use to find further details about your pipeline runs, such as the logs of your steps. For any runs executed on Kubeflow, you can get the URL to the Kubeflow UI in Python using the following code snippet: ```python from zenml.client import Client pipeline_run = Client().get_pipeline_run("") orchestrator_url = pipeline_run.run_metadata["orchestrator_url"] ``` #### Additional configuration For additional configuration of the Kubeflow orchestrator, you can pass `KubeflowOrchestratorSettings` which allows you to configure (among others) the following attributes: * `client_args`: Arguments to pass when initializing the KFP client. * `user_namespace`: The user namespace to use when creating experiments and runs. * `pod_settings`: Node selectors, affinity, and tolerations to apply to the Kubernetes Pods running your pipeline. These can be either specified using the Kubernetes model objects or as dictionaries. ```python from zenml.integrations.kubeflow.flavors.kubeflow_orchestrator_flavor import KubeflowOrchestratorSettings from kubernetes.client.models import V1Toleration kubeflow_settings = KubeflowOrchestratorSettings( client_args={}, user_namespace="my_namespace", pod_settings={ "affinity": { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [ { "matchExpressions": [ { "key": "node.kubernetes.io/name", "operator": "In", "values": ["my_powerful_node_group"], } ] } ] } } }, "tolerations": [ V1Toleration( key="node.kubernetes.io/name", operator="Equal", value="", effect="NoSchedule" ) ] } ) @pipeline( settings={ "orchestrator": kubeflow_settings } ) ... ``` Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-kubeflow/#zenml.integrations.kubeflow.flavors.kubeflow\_orchestrator\_flavor.KubeflowOrchestratorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings. #### Enabling CUDA for GPU-backed hardware Note that if you wish to use this orchestrator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration. ### Important Note for Multi-Tenancy Deployments Kubeflow has a notion of [multi-tenancy](https://www.kubeflow.org/docs/components/multi-tenancy/overview/) built into its deployment. Kubeflow's multi-user isolation simplifies user operations because each user only views and edited the Kubeflow components and model artifacts defined in their configuration. Using the ZenML Kubeflow orchestrator on a multi-tenant deployment without any settings will result in the following error: ```shell HTTP response body: {"error":"Invalid input error: Invalid resource references for experiment. ListExperiment requires filtering by namespace.","code":3,"message":"Invalid input error: Invalid resource references for experiment. ListExperiment requires filtering by namespace.","details":[{"@type":"type.googleapis.com/api.Error","error_message":"Invalid resource references for experiment. ListExperiment requires filtering by namespace.","error_details":"Invalid input error: Invalid resource references for experiment. ListExperiment requires filtering by namespace."}]} ``` In order to get it to work, we need to leverage the `KubeflowOrchestratorSettings` referenced above. By setting the namespace option, and by passing in the right authentication credentials to the Kubeflow Pipelines Client, we can make it work. First, when registering your Kubeflow orchestrator, please make sure to include the `kubeflow_hostname` parameter. The `kubeflow_hostname` **must end with the `/pipeline` post-fix**. ```shell zenml orchestrator register \ --flavor=kubeflow \ --kubeflow_hostname= # e.g. https://mykubeflow.example.com/pipeline ``` Then, ensure that you use the pass the right settings before triggering a pipeline run. The following snippet will prove useful: ```python import requests from zenml.client import Client from zenml.integrations.kubeflow.flavors.kubeflow_orchestrator_flavor import ( KubeflowOrchestratorSettings, ) NAMESPACE = "namespace_name" # This is the user namespace for the profile you want to use USERNAME = "admin" # This is the username for the profile you want to use PASSWORD = "abc123" # This is the password for the profile you want to use # Use client_username and client_password and ZenML will automatically fetch a session cookie kubeflow_settings = KubeflowOrchestratorSettings( client_username=USERNAME, client_password=PASSWORD, user_namespace=NAMESPACE ) # You can also pass the cookie in `client_args` directly # kubeflow_settings = KubeflowOrchestratorSettings( # client_args={"cookies": session_cookie}, user_namespace=NAMESPACE # ) @pipeline( settings={ "orchestrator": kubeflow_settings } ) : ... if "__name__" == "__main__": # Run the pipeline ``` Note that the above is also currently not tested on all Kubeflow versions, so there might be further bugs with older Kubeflow versions. In this case, please reach out to us on [Slack](https://zenml.io/slack). #### Using secrets in settings The above example encoded the username and password in plain text as settings. You can also set them as secrets. ```shell zenml secret create kubeflow_secret \ --username=admin \ --password=abc123 ``` And then you can use them in code: ```python # Use client_username and client_password and ZenML will automatically fetch a session cookie kubeflow_settings = KubeflowOrchestratorSettings( client_username="{{kubeflow_secret.username}}", # secret reference client_password="{{kubeflow_secret.password}}", # secret reference user_namespace="namespace_name" ) ``` See full documentation of using ZenML secrets [here](../../how-to/project-setup-and-management/interact-with-secrets.md). For more information and a full list of configurable attributes of the Kubeflow orchestrator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-kubeflow/#zenml.integrations.kubeflow.orchestrators.kubeflow\_orchestrator.KubeflowOrchestrator) .
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/kubernetes.md ================ --- description: Orchestrating your pipelines to run on Kubernetes clusters. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Kubernetes Orchestrator Using the ZenML `kubernetes` integration, you can orchestrate and scale your ML pipelines on a [Kubernetes](https://kubernetes.io/) cluster without writing a single line of Kubernetes code. This Kubernetes-native orchestrator is a minimalist, lightweight alternative to other distributed orchestrators like Airflow or Kubeflow. Overall, the Kubernetes orchestrator is quite similar to the Kubeflow orchestrator in that it runs each pipeline step in a separate Kubernetes pod. However, the orchestration of the different pods is not done by Kubeflow but by a separate master pod that orchestrates the step execution via topological sort. Compared to Kubeflow, this means that the Kubernetes-native orchestrator is faster and much simpler to start with since you do not need to install and maintain Kubeflow on your cluster. The Kubernetes-native orchestrator is an ideal choice for teams new to distributed orchestration that do not want to go with a fully-managed offering. However, since Kubeflow is much more mature, you should, in most cases, aim to move your pipelines to Kubeflow in the long run. A smooth way to production-grade orchestration could be to set up a Kubernetes cluster first and get started with the Kubernetes-native orchestrator. If needed, you can then install and set up Kubeflow later and simply switch out the orchestrator of your stack as soon as your full setup is ready. {% hint style="warning" %} This component is only meant to be used within the context of a [remote ZenML deployment scenario](../../getting-started/deploying-zenml/README.md). Usage with a local ZenML deployment may lead to unexpected behavior! {% endhint %} ### When to use it You should use the Kubernetes orchestrator if: * you're looking for a lightweight way of running your pipelines on Kubernetes. * you're not willing to maintain [Kubeflow Pipelines](kubeflow.md) on your Kubernetes cluster. * you're not interested in paying for managed solutions like [Vertex](vertex.md). ### How to deploy it The Kubernetes orchestrator requires a Kubernetes cluster in order to run. There are many ways to deploy a Kubernetes cluster using different cloud providers or on your custom infrastructure, and we can't possibly cover all of them, but you can check out our [our cloud guide](../../user-guide/cloud-guide/cloud-guide.md). If the above Kubernetes cluster is deployed remotely on the cloud, then another pre-requisite to use this orchestrator would be to deploy and connect to a [remote ZenML server](../../getting-started/deploying-zenml/README.md). ### How to use it To use the Kubernetes orchestrator, we need: * The ZenML `kubernetes` integration installed. If you haven't done so, run ```shell zenml integration install kubernetes ``` * [Docker](https://www.docker.com) installed and running. * [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) installed. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. * A [remote container registry](../container-registries/container-registries.md) as part of your stack. * A Kubernetes cluster [deployed](kubernetes.md#how-to-deploy-it) * [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) installed and the name of the Kubernetes configuration context which points to the target cluster (i.e. run`kubectl config get-contexts` to see a list of available contexts) . This is optional (see below). {% hint style="info" %} It is recommended that you set up [a Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) and use it to connect ZenML Stack Components to the remote Kubernetes cluster, especially If you are using a Kubernetes cluster managed by a cloud provider like AWS, GCP or Azure, This guarantees that your Stack is fully portable on other environments and your pipelines are fully reproducible. {% endhint %} We can then register the orchestrator and use it in our active stack. This can be done in two ways: 1. If you have [a Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) configured to access the remote Kubernetes cluster, you no longer need to set the `kubernetes_context` attribute to a local `kubectl` context. In fact, you don't need the local Kubernetes CLI at all. You can [connect the stack component to the Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md#connect-stack-components-to-resources) instead: ``` $ zenml orchestrator register --flavor kubernetes Running with active stack: 'default' (repository) Successfully registered orchestrator ``. $ zenml service-connector list-resources --resource-type kubernetes-cluster -e The following 'kubernetes-cluster' resources can be accessed by service connectors: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ e33c9fac-5daa-48b2-87bb-0187d3782cde β”‚ aws-iam-multi-eu β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ kubeflowmultitenant ┃ ┃ β”‚ β”‚ β”‚ β”‚ zenbox ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ ed528d5a-d6cb-4fc4-bc52-c3d2d01643e5 β”‚ aws-iam-multi-us β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ zenhacks-cluster ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ 1c54b32a-4889-4417-abbd-42d3ace3d03a β”‚ gcp-sa-multi β”‚ πŸ”΅ gcp β”‚ πŸŒ€ kubernetes-cluster β”‚ zenml-test-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┛ $ zenml orchestrator connect --connector aws-iam-multi-us Running with active stack: 'default' (repository) Successfully connected orchestrator `` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼──────────────────┼────────────────┼───────────────────────┼──────────────────┨ ┃ ed528d5a-d6cb-4fc4-bc52-c3d2d01643e5 β”‚ aws-iam-multi-us β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ zenhacks-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┛ # Register and activate a stack with the new orchestrator $ zenml stack register -o ... --set ``` 2. if you don't have a Service Connector on hand and you don't want to [register one](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md#register-service-connectors) , the local Kubernetes `kubectl` client needs to be configured with a configuration context pointing to the remote cluster. The `kubernetes_context` stack component must also be configured with the value of that context: ```shell zenml orchestrator register \ --flavor=kubernetes \ --kubernetes_context= # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` {% hint style="info" %} ZenML will build a Docker image called `/zenml:` which includes your code and use it to run your pipeline steps in Kubernetes. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. {% endhint %} You can now run any ZenML pipeline using the Kubernetes orchestrator: ```shell python file_that_runs_a_zenml_pipeline.py ``` If all went well, you should now see the logs of all Kubernetes pods in your terminal, and when running `kubectl get pods -n zenml`, you should also see that a pod was created in your cluster for each pipeline step. #### Interacting with pods via kubectl For debugging, it can sometimes be handy to interact with the Kubernetes pods directly via kubectl. To make this easier, we have added the following labels to all pods: * `run`: the name of the ZenML run. * `pipeline`: the name of the ZenML pipeline associated with this run. E.g., you can use these labels to manually delete all pods related to a specific pipeline: ```shell kubectl delete pod -n zenml -l pipeline=kubernetes_example_pipeline ``` #### Additional configuration The Kubernetes orchestrator will by default use a Kubernetes namespace called `zenml` to run pipelines. In that namespace, it will automatically create a Kubernetes service account called `zenml-service-account` and grant it `edit` RBAC role in that namespace. To customize these settings, you can configure the following additional attributes in the Kubernetes orchestrator: * `kubernetes_namespace`: The Kubernetes namespace to use for running the pipelines. The namespace must already exist in the Kubernetes cluster. * `service_account_name`: The name of a Kubernetes service account to use for running the pipelines. If configured, it must point to an existing service account in the default or configured `namespace` that has associated RBAC roles granting permissions to create and manage pods in that namespace. This can also be configured as an individual pipeline setting in addition to the global orchestrator setting. For additional configuration of the Kubernetes orchestrator, you can pass `KubernetesOrchestratorSettings` which allows you to configure (among others) the following attributes: * `pod_settings`: Node selectors, labels, affinity, and tolerations, and image pull secrets to apply to the Kubernetes Pods running the steps of your pipeline. These can be either specified using the Kubernetes model objects or as dictionaries. * `orchestrator_pod_settings`: Node selectors, labels, affinity, and tolerations, and image pull secrets to apply to the Kubernetes Pod that is responsible for orchestrating the pipeline and starting the other Pods. These can be either specified using the Kubernetes model objects or as dictionaries. ```python from zenml.integrations.kubernetes.flavors.kubernetes_orchestrator_flavor import KubernetesOrchestratorSettings from kubernetes.client.models import V1Toleration kubernetes_settings = KubernetesOrchestratorSettings( pod_settings={ "node_selectors": { "cloud.google.com/gke-nodepool": "ml-pool", "kubernetes.io/arch": "amd64" }, "affinity": { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [ { "matchExpressions": [ { "key": "gpu-type", "operator": "In", "values": ["nvidia-tesla-v100", "nvidia-tesla-p100"] } ] } ] } } }, "tolerations": [ V1Toleration( key="gpu", operator="Equal", value="present", effect="NoSchedule" ), V1Toleration( key="high-priority", operator="Exists", effect="PreferNoSchedule" ) ], "resources": { "requests": { "cpu": "2", "memory": "4Gi", "nvidia.com/gpu": "1" }, "limits": { "cpu": "4", "memory": "8Gi", "nvidia.com/gpu": "1" } }, "annotations": { "prometheus.io/scrape": "true", "prometheus.io/port": "8080" }, "volumes": [ { "name": "data-volume", "persistentVolumeClaim": { "claimName": "ml-data-pvc" } }, { "name": "config-volume", "configMap": { "name": "ml-config" } } ], "volume_mounts": [ { "name": "data-volume", "mountPath": "/mnt/data" }, { "name": "config-volume", "mountPath": "/etc/ml-config", "readOnly": True } ], "host_ipc": True, "image_pull_secrets": ["regcred", "gcr-secret"], "labels": { "app": "ml-pipeline", "environment": "production", "team": "data-science" } }, orchestrator_pod_settings={ "node_selectors": { "cloud.google.com/gke-nodepool": "orchestrator-pool" }, "resources": { "requests": { "cpu": "1", "memory": "2Gi" }, "limits": { "cpu": "2", "memory": "4Gi" } }, "labels": { "app": "zenml-orchestrator", "component": "pipeline-runner" } }, kubernetes_namespace="ml-pipelines", service_account_name="zenml-pipeline-runner" ) @pipeline( settings={ "orchestrator": kubernetes_settings } ) def my_kubernetes_pipeline(): # Your pipeline steps here ... ``` #### Define settings on the step level You can also define settings on the step level, which will override the settings defined at the pipeline level. This is helpful when you want to run a specific step with a different configuration like affinity for more powerful hardware or a different Kubernetes service account. Learn more about the hierarchy of settings [here](../../how-to/pipeline-development/use-configuration-files/configuration-hierarchy.md). ```python k8s_settings = KubernetesOrchestratorSettings( pod_settings={ "node_selectors": { "cloud.google.com/gke-nodepool": "gpu-pool", }, "tolerations": [ V1Toleration( key="gpu", operator="Equal", value="present", effect="NoSchedule" ), ] } ) @step(settings={"orchestrator": k8s_settings}) def train_model(data: dict) -> None: ... @pipeline() def simple_ml_pipeline(parameter: int): ... ``` This code will now run the `train_model` step on a GPU-enabled node in the `gpu-pool` node pool while the rest of the pipeline can run on ordinary nodes. Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-kubernetes/#zenml.integrations.kubernetes.flavors.kubernetes\_orchestrator\_flavor.KubernetesOrchestratorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings. For more information and a full list of configurable attributes of the Kubernetes orchestrator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-kubernetes/#zenml.integrations.kubernetes.orchestrators.kubernetes\_orchestrator.KubernetesOrchestrator) . #### Enabling CUDA for GPU-backed hardware Note that if you wish to use this orchestrator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/lightning.md ================ --- description: Orchestrating your pipelines to run on Lightning AI. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Lightning AI Orchestrator [Lightning AI Studio](https://lightning.ai/) is a platform that simplifies the development and deployment of AI applications. The Lightning AI orchestrator is an integration provided by ZenML that allows you to run your pipelines on Lightning AI's infrastructure, leveraging its scalable compute resources and managed environment. {% hint style="warning" %} This component is only meant to be used within the context of a [remote ZenML deployment scenario](../../getting-started/deploying-zenml/README.md). Usage with a local ZenML deployment may lead to unexpected behavior! {% endhint %} ## When to use it * You are looking for a fast and easy way to run your pipelines on GPU instances * You're already using Lightning AI for your machine learning projects * You want to leverage Lightning AI's managed infrastructure for running your pipelines * You're looking for a solution that simplifies the deployment and scaling of your ML workflows * You want to take advantage of Lightning AI's optimizations for machine learning workloads ## How to deploy it To use the [Lightning AI Studio](https://lightning.ai/) orchestrator, you need to have a Lightning AI account and the necessary credentials. You don't need to deploy any additional infrastructure, as the orchestrator will use Lightning AI's managed resources. ## How it works The Lightning AI orchestrator is a ZenML orchestrator that runs your pipelines on Lightning AI's infrastructure. When you run a pipeline with the Lightning AI orchestrator, ZenML will archive your current ZenML repository and upload it to the Lightning AI studio. Once the code is archived, using `lightning-sdk`, ZenML will create a new stduio in Lightning AI and upload the code to it. Then ZenML runs list of commands via `studio.run()` to prepare for the pipeline run (e.g. installing dependencies, setting up the environment). Finally, ZenML will run the pipeline on Lightning AI's infrastructure. * You can always use an already existing studio by specifying the `main_studio_name` in the `LightningOrchestratorSettings`. * The orchestartor supports a async mode, which means that the pipeline will be run in the background and you can check the status of the run in the ZenML Dashboard or the Lightning AI Studio. * You can specify a list of custom commands that will be executed before running the pipeline. This can be useful for installing dependencies or setting up the environment. * The orchestrator supports both CPU and GPU machine types. You can specify the machine type in the `LightningOrchestratorSettings`. ## How to use it To use the Lightning AI orchestrator, you need: * The ZenML `lightning` integration installed. If you haven't done so, run ```shell zenml integration install lightning ``` * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. * [Lightning AI credentials](#lightning-ai-credentials) ### Lightning AI credentials You will need the following credentials to use the Lightning AI orchestrator: * `LIGHTNING_USER_ID`: Your Lightning AI user ID * `LIGHTNING_API_KEY`: Your Lightning AI API key * `LIGHTNING_USERNAME`: Your Lightning AI username (optional) * `LIGHTNING_TEAMSPACE`: Your Lightning AI teamspace (optional) * `LIGHTNING_ORG`: Your Lightning AI organization (optional) To find these credentials, log in to your [Lightning AI](https://lightning.ai/) account and click on your avatar in the top right corner. Then click on "Global Settings". There are some tabs you can click on the left hand side. Click on the one that says "Keys" and you will see two ways to get your credentials. The 'Login via CLI' will give you the `LIGHTNING_USER_ID` and `LIGHTNING_API_KEY`. You can set these credentials as environment variables or you can set them when registering the orchestrator: ```shell zenml orchestrator register lightning_orchestrator \ --flavor=lightning \ --user_id= \ --api_key= \ --username= \ # optional --teamspace= \ # optional --organization= # optional ``` We can then register the orchestrator and use it in our active stack: ```bash # Register and activate a stack with the new orchestrator zenml stack register lightning_stack -o lightning_orchestrator ... --set ``` You can configure the orchestrator at pipeline level, using the `orchestrator` parameter. ```python from zenml.integrations.lightning.flavors.lightning_orchestrator_flavor import LightningOrchestratorSettings lightning_settings = LightningOrchestratorSettings( main_studio_name="my_studio", machine_type="cpu", async_mode=True, custom_commands=["pip install -r requirements.txt", "do something else"] ) @pipeline( settings={ "orchestrator.lightning": lightning_settings } ) def my_pipeline(): ... ``` {% hint style="info" %} ZenML will archive the current zenml repository (the code within the path where you run `zenml init`) and upload it to the Lightning AI studio. For this reason you need make sure that you have run `zenml init` in the same repository root directory where you are running your pipeline. {% endhint %} ![Lightning AI studio VSCode](../../.gitbook/assets/lightning_studio_vscode.png) {% hint style="info" %} The `custom_commands` attribute allows you to specify a list of shell commands that will be executed before running the pipeline. This can be useful for installing dependencies or setting up the environment, The commands will be executed in the root directory of the uploaded and extracted ZenML repository. {% endhint %} You can now run any ZenML pipeline using the Lightning AI orchestrator: ```shell python file_that_runs_a_zenml_pipeline.py ``` ### Lightning AI UI Lightning AI provides its own UI where you can monitor and manage your running applications, including the pipelines orchestrated by ZenML. ![Lightning AI Studio](../../.gitbook/assets/lightning_studio_ui.png) For any runs executed on Lightning AI, you can get the URL to the Lightning AI UI in Python using the following code snippet: ```python from zenml.client import Client pipeline_run = Client().get_pipeline_run("") orchestrator_url = pipeline_run.run_metadata["orchestrator_url"].value ``` ### Additional configuration For additional configuration of the Lightning AI orchestrator, you can pass `LightningOrchestratorSettings` which allows you to configure various aspects of the Lightning AI execution environment: ```python from zenml.integrations.lightning.flavors.lightning_orchestrator_flavor import LightningOrchestratorSettings lightning_settings = LightningOrchestratorSettings( main_studio_name="my_studio", machine_type="cpu", async_mode=True, custom_commands=["pip install -r requirements.txt", "do something else"] ) ``` These settings can then be specified on either a pipeline-level or step-level: ```python # Either specify on pipeline-level @pipeline( settings={ "orchestrator.lightning": lightning_settings } ) def my_pipeline(): ... # OR specify settings on step-level @step( settings={ "orchestrator.lightning": lightning_settings } ) def my_step(): ... ``` Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-lightning/#zenml.integrations.lightning.flavors.lightning_orchestrator_flavor.LightningOrchestratorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings. To use GPUs with the Lightning AI orchestrator, you need to specify a GPU-enabled machine type in your settings: ```python lightning_settings = LightningOrchestratorSettings( machine_type="gpu", # or `A10G` e.g. ) ``` Make sure to check [Lightning AI's documentation](https://lightning.ai/docs/overview/studios/change-gpus) for the available GPU-enabled machine types and their specifications.
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/local-docker.md ================ --- description: Orchestrating your pipelines to run in Docker. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Local Docker Orchestrator The local Docker orchestrator is an [orchestrator](./orchestrators.md) flavor that comes built-in with ZenML and runs your pipelines locally using Docker. ### When to use it You should use the local Docker orchestrator if: * you want the steps of your pipeline to run locally in isolated environments. * you want to debug issues that happen when running your pipeline in Docker containers without waiting and paying for remote infrastructure. ### How to deploy it To use the local Docker orchestrator, you only need to have [Docker](https://www.docker.com/) installed and running. ### How to use it To use the local Docker orchestrator, we can register it and use it in our active stack: ```shell zenml orchestrator register --flavor=local_docker # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` You can now run any ZenML pipeline using the local Docker orchestrator: ```shell python file_that_runs_a_zenml_pipeline.py ``` #### Additional configuration For additional configuration of the Local Docker orchestrator, you can pass `LocalDockerOrchestratorSettings` when defining or running your pipeline. Check out the [SDK docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-orchestrators/#zenml.orchestrators.local\_docker.local\_docker\_orchestrator.LocalDockerOrchestratorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings. A full list of what can be passed in via the `run_args` can be found [in the Docker Python SDK documentation](https://docker-py.readthedocs.io/en/stable/containers.html). For more information and a full list of configurable attributes of the local Docker orchestrator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-orchestrators/#zenml.orchestrators.local\_docker.local\_docker\_orchestrator.LocalDockerOrchestrator) . For example, if you wanted to specify the CPU count available for the Docker image (note: only configurable for Windows), you could write a simple pipeline like the following: ```python from zenml import step, pipeline from zenml.orchestrators.local_docker.local_docker_orchestrator import ( LocalDockerOrchestratorSettings, ) @step def return_one() -> int: return 1 settings = { "orchestrator": LocalDockerOrchestratorSettings( run_args={"cpu_count": 3} ) } @pipeline(settings=settings) def simple_pipeline(): return_one() ``` #### Enabling CUDA for GPU-backed hardware Note that if you wish to use this orchestrator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/local.md ================ --- description: Orchestrating your pipelines to run locally. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Local Orchestrator The local orchestrator is an [orchestrator](./orchestrators.md) flavor that comes built-in with ZenML and runs your pipelines locally. ### When to use it The local orchestrator is part of your default stack when you're first getting started with ZenML. Due to it running locally on your machine, it requires no additional setup and is easy to use and debug. You should use the local orchestrator if: * you're just getting started with ZenML and want to run pipelines without setting up any cloud infrastructure. * you're writing a new pipeline and want to experiment and debug quickly ### How to deploy it The local orchestrator comes with ZenML and works without any additional setup. ### How to use it To use the local orchestrator, we can register it and use it in our active stack: ```shell zenml orchestrator register --flavor=local # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` You can now run any ZenML pipeline using the local orchestrator: ```shell python file_that_runs_a_zenml_pipeline.py ``` For more information and a full list of configurable attributes of the local orchestrator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-orchestrators/#zenml.orchestrators.local.local\_orchestrator.LocalOrchestrator) .
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/orchestrators.md ================ --- icon: train-track description: Orchestrating the execution of ML pipelines. --- # Orchestrators The orchestrator is an essential component in any MLOps stack as it is responsible for running your machine learning pipelines. To do so, the orchestrator provides an environment that is set up to execute the steps of your pipeline. It also makes sure that the steps of your pipeline only get executed once all their inputs (which are outputs of previous steps of your pipeline) are available. {% hint style="info" %} Many of ZenML's remote orchestrators build [Docker](https://www.docker.com/) images in order to transport and execute your pipeline code. If you want to learn more about how Docker images are built by ZenML, check out [this guide](../../how-to/customize-docker-builds/README.md). {% endhint %} ### When to use it The orchestrator is a mandatory component in the ZenML stack. It is used to store all artifacts produced by pipeline runs, and you are required to configure it in all of your stacks. ### Orchestrator Flavors Out of the box, ZenML comes with a `local` orchestrator already part of the default stack that runs pipelines locally. Additional orchestrators are provided by integrations: | Orchestrator | Flavor | Integration | Notes | |---------------------------------------------|----------------|-------------------|-------------------------------------------------------------------------| | [LocalOrchestrator](local.md) | `local` | _built-in_ | Runs your pipelines locally. | | [LocalDockerOrchestrator](local-docker.md) | `local_docker` | _built-in_ | Runs your pipelines locally using Docker. | | [KubernetesOrchestrator](kubernetes.md) | `kubernetes` | `kubernetes` | Runs your pipelines in Kubernetes clusters. | | [KubeflowOrchestrator](kubeflow.md) | `kubeflow` | `kubeflow` | Runs your pipelines using Kubeflow. | | [VertexOrchestrator](vertex.md) | `vertex` | `gcp` | Runs your pipelines in Vertex AI. | | [SagemakerOrchestrator](sagemaker.md) | `sagemaker` | `aws` | Runs your pipelines in Sagemaker. | | [AzureMLOrchestrator](azureml.md) | `azureml` | `azure` | Runs your pipelines in AzureML. | | [TektonOrchestrator](tekton.md) | `tekton` | `tekton` | Runs your pipelines using Tekton. | | [AirflowOrchestrator](airflow.md) | `airflow` | `airflow` | Runs your pipelines using Airflow. | | [SkypilotAWSOrchestrator](skypilot-vm.md) | `vm_aws` | `skypilot[aws]` | Runs your pipelines in AWS VMs using SkyPilot | | [SkypilotGCPOrchestrator](skypilot-vm.md) | `vm_gcp` | `skypilot[gcp]` | Runs your pipelines in GCP VMs using SkyPilot | | [SkypilotAzureOrchestrator](skypilot-vm.md) | `vm_azure` | `skypilot[azure]` | Runs your pipelines in Azure VMs using SkyPilot | | [HyperAIOrchestrator](hyperai.md) | `hyperai` | `hyperai` | Runs your pipeline in HyperAI.ai instances. | | [Custom Implementation](custom.md) | _custom_ | | Extend the orchestrator abstraction and provide your own implementation | If you would like to see the available flavors of orchestrators, you can use the command: ```shell zenml orchestrator flavor list ``` ### How to use it You don't need to directly interact with any ZenML orchestrator in your code. As long as the orchestrator that you want to use is part of your active [ZenML stack](../../user-guide/production-guide/understand-stacks.md), using the orchestrator is as simple as executing a Python file that [runs a ZenML pipeline](../../user-guide/starter-guide/starter-project.md): ```shell python file_that_runs_a_zenml_pipeline.py ``` #### Inspecting Runs in the Orchestrator UI If your orchestrator comes with a separate user interface (for example Kubeflow, Airflow, Vertex), you can get the URL to the orchestrator UI of a specific pipeline run using the following code snippet: ```python from zenml.client import Client pipeline_run = Client().get_pipeline_run("") orchestrator_url = pipeline_run.run_metadata["orchestrator_url"].value ``` #### Specifying per-step resources If your steps require the orchestrator to execute them on specific hardware, you can specify them on your steps as described [here](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md). If your orchestrator of choice or the underlying hardware doesn't support this, you can also take a look at [step operators](../step-operators/step-operators.md).
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/sagemaker.md ================ --- description: Orchestrating your pipelines to run on Amazon Sagemaker. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # AWS Sagemaker Orchestrator [Sagemaker Pipelines](https://aws.amazon.com/sagemaker/pipelines) is a serverless ML workflow tool running on AWS. It is an easy way to quickly run your code in a production-ready, repeatable cloud orchestrator that requires minimal setup without provisioning and paying for standby compute. {% hint style="warning" %} This component is only meant to be used within the context of a [remote ZenML deployment scenario](../../getting-started/deploying-zenml/README.md). Usage with a local ZenML deployment may lead to unexpected behavior! {% endhint %} ## When to use it You should use the Sagemaker orchestrator if: * you're already using AWS. * you're looking for a proven production-grade orchestrator. * you're looking for a UI in which you can track your pipeline runs. * you're looking for a managed solution for running your pipelines. * you're looking for a serverless solution for running your pipelines. ## How it works The ZenML Sagemaker orchestrator works with [Sagemaker Pipelines](https://aws.amazon.com/sagemaker/pipelines), which can be used to construct machine learning pipelines. Under the hood, for each ZenML pipeline step, it creates a SageMaker `PipelineStep`, which contains a Sagemaker Processing job. Currently, other step types are not supported. ## How to deploy it {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including a Sagemaker orchestrator? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), the [stack registration wizard](../../how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md), or [the ZenML AWS Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} In order to use a Sagemaker AI orchestrator, you need to first deploy [ZenML to the cloud](../../getting-started/deploying-zenml/README.md). It would be recommended to deploy ZenML in the same region as you plan on using for Sagemaker, but it is not necessary to do so. You must ensure that you are connected to the remote ZenML server before using this stack component. The only other thing necessary to use the ZenML Sagemaker orchestrator is enabling the relevant permissions for your particular role. ## How to use it To use the Sagemaker orchestrator, we need: * The ZenML `aws` and `s3` integrations installed. If you haven't done so, run ```shell zenml integration install aws s3 ``` * [Docker](https://www.docker.com) installed and running. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack (configured with an `authentication_secret` attribute). * A [remote container registry](../container-registries/container-registries.md) as part of your stack. * An IAM role or user with [an `AmazonSageMakerFullAccess` managed policy](https://docs.aws.amazon.com/sagemaker/latest/dg/security-iam-awsmanpol.html) applied to it as well as `sagemaker.amazonaws.com` added as a Principal Service. Full details on these permissions can be found [here](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html) or use the ZenML recipe (when available) which will set up the necessary permissions for you. * The local client (whoever is running the pipeline) will also have to have the necessary permissions or roles to be able to launch Sagemaker jobs. (This would be covered by the `AmazonSageMakerFullAccess` policy suggested above.) There are three ways you can authenticate your orchestrator and link it to the IAM role you have created: {% tabs %} {% tab title="Authentication via Service Connector" %} The recommended way to authenticate your SageMaker orchestrator is by registering an [AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md) and connecting it to your SageMaker orchestrator: ```shell zenml service-connector register --type aws -i zenml orchestrator register \ --flavor=sagemaker \ --execution_role= zenml orchestrator connect --connector zenml stack register -o ... --set ``` {% endtab %} {% tab title="Explicit Authentication" %} Instead of creating a service connector, you can also configure your AWS authentication credentials directly in the orchestrator: ```shell zenml orchestrator register \ --flavor=sagemaker \ --execution_role= \ --aws_access_key_id=... --aws_secret_access_key=... --region=... zenml stack register -o ... --set ``` See the [`SagemakerOrchestratorConfig` SDK Docs](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-aws/#zenml.integrations.aws.flavors.sagemaker_orchestrator_flavor.SagemakerOrchestratorSettings) for more information on available configuration options. {% endtab %} {% tab title="Implicit Authentication" %} If you neither connect your orchestrator to a service connector nor configure credentials explicitly, ZenML will try to implicitly authenticate to AWS via the `default` profile in your local [AWS configuration file](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html). ```shell zenml orchestrator register \ --flavor=sagemaker \ --execution_role= zenml stack register -o ... --set python run.py # Authenticates with `default` profile in `~/.aws/config` ``` {% endtab %} {% endtabs %} {% hint style="info" %} ZenML will build a Docker image called `/zenml:` which includes your code and use it to run your pipeline steps in Sagemaker. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. {% endhint %} You can now run any ZenML pipeline using the Sagemaker orchestrator: ```shell python run.py ``` If all went well, you should now see the following output: ``` Steps can take 5-15 minutes to start running when using the Sagemaker Orchestrator. Your orchestrator 'sagemaker' is running remotely. Note that the pipeline run will only show up on the ZenML dashboard once the first step has started executing on the remote infrastructure. ``` {% hint style="warning" %} If it is taking more than 15 minutes for your run to show up, it might be that a setup error occurred in SageMaker before the pipeline could be started. Checkout the [Debugging SageMaker Pipelines](sagemaker.md#debugging-sagemaker-pipelines) section for more information on how to debug this. {% endhint %} ### Sagemaker UI Sagemaker comes with its own UI that you can use to find further details about your pipeline runs, such as the logs of your steps. To access the Sagemaker Pipelines UI, you will have to launch Sagemaker Studio via the AWS Sagemaker UI. Make sure that you are launching it from within your desired AWS region. ![Sagemaker Studio launch](../../.gitbook/assets/sagemaker-studio-launch.png) Once the Studio UI has launched, click on the 'Pipeline' button on the left side. From there you can view the pipelines that have been launched via ZenML: ![Sagemaker Studio Pipelines](../../.gitbook/assets/sagemakerUI.png) ### Debugging SageMaker Pipelines If your SageMaker pipeline encounters an error before the first ZenML step starts, the ZenML run will not appear in the ZenML dashboard. In such cases, use the [SageMaker UI](sagemaker.md#sagemaker-ui) to review the error message and logs. Here's how: * Open the corresponding pipeline in the SageMaker UI as shown in the [SageMaker UI Section](sagemaker.md#sagemaker-ui), * Open the execution, * Click on the failed step in the pipeline graph, * Go to the 'Output' tab to see the error message or to 'Logs' to see the logs. ![SageMaker Studio Logs](../../.gitbook/assets/sagemaker-logs.png) Alternatively, for a more detailed view of log messages during SageMaker pipeline executions, consider using [Amazon CloudWatch](https://aws.amazon.com/cloudwatch/): * Search for 'CloudWatch' in the AWS console search bar. * Navigate to 'Logs > Log groups.' * Open the '/aws/sagemaker/ProcessingJobs' log group. * Here, you can find log streams for each step of your SageMaker pipeline executions. ![SageMaker CloudWatch Logs](../../.gitbook/assets/sagemaker-cloudwatch-logs.png) ### Run pipelines on a schedule The ZenML Sagemaker orchestrator doesn't currently support running pipelines on a schedule. We maintain a public roadmap for ZenML, which you can find [here](https://zenml.io/roadmap). We welcome community contributions (see more [here](https://github.com/zenml-io/zenml/blob/main/CONTRIBUTING.md)) so if you want to enable scheduling for Sagemaker, please [do let us know](https://zenml.io/slack)! ### Configuration at pipeline or step level When running your ZenML pipeline with the Sagemaker orchestrator, the configuration set when configuring the orchestrator as a ZenML component will be used by default. However, it is possible to provide additional configuration at the pipeline or step level. This allows you to run whole pipelines or individual steps with alternative configurations. For example, this allows you to run the training process with a heavier, GPU-enabled instance type, while running other steps with lighter instances. Additional configuration for the Sagemaker orchestrator can be passed via `SagemakerOrchestratorSettings`. Here, it is possible to configure `processor_args`, which is a dictionary of arguments for the Processor. For available arguments, see the [Sagemaker documentation](https://sagemaker.readthedocs.io/en/stable/api/training/processing.html#sagemaker.processing.Processor) . Currently, it is not possible to provide custom configuration for the following attributes: * `image_uri` * `instance_count` * `sagemaker_session` * `entrypoint` * `base_job_name` * `env` For example, settings can be provided in the following way: ```python sagemaker_orchestrator_settings = SagemakerOrchestratorSettings( instance_type="ml.m5.large", volume_size_in_gb=30, ) ``` They can then be applied to a step as follows: ```python @step(settings={"orchestrator": sagemaker_orchestrator_settings}) ``` For example, if your ZenML component is configured to use `ml.c5.xlarge` with 400GB additional storage by default, all steps will use it except for the step above, which will use `ml.t3.medium` (for Processing Steps) or `ml.m5.xlarge` (for Training Steps) with 30GB additional storage. See the next section for details on how ZenML decides which Sagemaker Step type to use. Check out [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings in general. For more information and a full list of configurable attributes of the Sagemaker orchestrator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-aws/#zenml.integrations.aws.flavors.sagemaker_orchestrator_flavor.SagemakerOrchestratorSettings) . ### Using Warm Pools for your pipelines [Warm Pools in SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/train-warm-pools.html) can significantly reduce the startup time of your pipeline steps, leading to faster iterations and improved development efficiency. This feature keeps compute instances in a "warm" state, ready to quickly start new jobs. To enable Warm Pools, use the [`SagemakerOrchestratorSettings`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-aws/#zenml.integrations.aws.flavors.sagemaker_orchestrator_flavor.SagemakerOrchestratorSettings) class: ```python sagemaker_orchestrator_settings = SagemakerOrchestratorSettings( keep_alive_period_in_seconds = 300, # 5 minutes, default value ) ``` This configuration keeps instances warm for 5 minutes after each job completes, allowing subsequent jobs to start faster if initiated within this timeframe. The reduced startup time can be particularly beneficial for iterative development processes or frequently run pipelines. If you prefer not to use Warm Pools, you can explicitly disable them: ```python sagemaker_orchestrator_settings = SagemakerOrchestratorSettings( keep_alive_period_in_seconds = None, ) ``` By default, the SageMaker orchestrator uses Training Steps where possible, which can offer performance benefits and better integration with SageMaker's training capabilities. To disable this behavior: ```python sagemaker_orchestrator_settings = SagemakerOrchestratorSettings( use_training_step = False ) ``` These settings allow you to fine-tune your SageMaker orchestrator configuration, balancing between faster startup times with Warm Pools and more control over resource usage. By optimizing these settings, you can potentially reduce overall pipeline runtime and improve your development workflow efficiency. #### S3 data access in ZenML steps In Sagemaker jobs, it is possible to [access data that is located in S3](https://docs.aws.amazon.com/sagemaker/latest/dg/model-access-training-data.html). Similarly, it is possible to write data from a job to a bucket. The ZenML Sagemaker orchestrator supports this via the `SagemakerOrchestratorSettings` and hence at component, pipeline, and step levels. **Import: S3 -> job** Importing data can be useful when large datasets are available in S3 for training, for which manual copying can be cumbersome. Sagemaker supports `File` (default) and `Pipe` mode, with which data is either fully copied before the job starts or piped on the fly. See the Sagemaker documentation referenced above for more information about these modes. Note that data import and export can be used jointly with `processor_args` for maximum flexibility. A simple example of importing data from S3 to the Sagemaker job is as follows: ```python sagemaker_orchestrator_settings = SagemakerOrchestratorSettings( input_data_s3_mode="File", input_data_s3_uri="s3://some-bucket-name/folder" ) ``` In this case, data will be available at `/opt/ml/processing/input/data` within the job. It is also possible to split your input over channels. This can be useful if the dataset is already split in S3, or maybe even located in different buckets. ```python sagemaker_orchestrator_settings = SagemakerOrchestratorSettings( input_data_s3_mode="File", input_data_s3_uri={ "train": "s3://some-bucket-name/training_data", "val": "s3://some-bucket-name/validation_data", "test": "s3://some-other-bucket-name/testing_data" } ) ``` Here, the data will be available in `/opt/ml/processing/input/data/train`, `/opt/ml/processing/input/data/val` and `/opt/ml/processing/input/data/test`. In the case of using `Pipe` for `input_data_s3_mode`, a file path specifying the pipe will be available as per the description written [here](https://docs.aws.amazon.com/sagemaker/latest/dg/model-access-training-data.html#model-access-training-data-input-modes) . An example of using this pipe file within a Python script can be found [here](https://github.com/aws/amazon-sagemaker-examples/blob/main/advanced\_functionality/pipe\_bring\_your\_own/train.py) . **Export: job -> S3** Data from within the job (e.g. produced by the training process, or when preprocessing large data) can be exported as well. The structure is highly similar to that of importing data. Copying data to S3 can be configured with `output_data_s3_mode`, which supports `EndOfJob` (default) and `Continuous`. In the simple case, data in `/opt/ml/processing/output/data` will be copied to S3 at the end of a job: ```python sagemaker_orchestrator_settings = SagemakerOrchestratorSettings( output_data_s3_mode="EndOfJob", output_data_s3_uri="s3://some-results-bucket-name/results" ) ``` In a more complex case, data in `/opt/ml/processing/output/data/metadata` and `/opt/ml/processing/output/data/checkpoints` will be written away continuously: ```python sagemaker_orchestrator_settings = SagemakerOrchestratorSettings( output_data_s3_mode="Continuous", output_data_s3_uri={ "metadata": "s3://some-results-bucket-name/metadata", "checkpoints": "s3://some-results-bucket-name/checkpoints" } ) ``` {% hint style="warning" %} Using multichannel output or output mode except `EndOfJob` will make it impossible to use TrainingStep and also Warm Pools. See corresponding section of this document for details. {% endhint %} ### Tagging SageMaker Pipeline Executions and Jobs The SageMaker orchestrator allows you to add tags to your pipeline executions and individual jobs. Here's how you can apply tags at both the pipeline and step levels: ```python from zenml import pipeline, step from zenml.integrations.aws.flavors.sagemaker_orchestrator_flavor import SagemakerOrchestratorSettings # Define settings for the pipeline pipeline_settings = SagemakerOrchestratorSettings( pipeline_tags={ "project": "my-ml-project", "environment": "production", } ) # Define settings for a specific step step_settings = SagemakerOrchestratorSettings( tags={ "step": "data-preprocessing", "owner": "data-team" } ) @step(settings={"orchestrator": step_settings}) def preprocess_data(): # Your preprocessing code here pass @pipeline(settings={"orchestrator": pipeline_settings}) def my_training_pipeline(): preprocess_data() # Other steps... # Run the pipeline my_training_pipeline() ``` In this example: - The `pipeline_tags` are applied to the entire SageMaker pipeline object. SageMaker automatically applies the pipeline_tags to all its associated jobs. - The `tags` in `step_settings` are applied to the specific SageMaker job for the `preprocess_data` step. This approach allows for more granular tagging, giving you flexibility in how you categorize and manage your SageMaker resources. You can view and manage these tags in the AWS Management Console, CLI, or API calls related to your SageMaker resources. ### Enabling CUDA for GPU-backed hardware Note that if you wish to use this orchestrator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/skypilot-vm.md ================ --- description: Orchestrating your pipelines to run on VMs using SkyPilot. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Skypilot VM Orchestrator The SkyPilot VM Orchestrator is an integration provided by ZenML that allows you to provision and manage virtual machines (VMs) on any cloud provider supported by the [SkyPilot framework](https://skypilot.readthedocs.io/en/latest/index.html). This integration is designed to simplify the process of running machine learning workloads on the cloud, offering cost savings, high GPU availability, and managed execution, We recommend using the SkyPilot VM Orchestrator if you need access to GPUs for your workloads, but don't want to deal with the complexities of managing cloud infrastructure or expensive managed solutions. {% hint style="warning" %} This component is only meant to be used within the context of a [remote ZenML deployment scenario](../../getting-started/deploying-zenml/README.md). Usage with a local ZenML deployment may lead to unexpected behavior! {% endhint %} ## When to use it You should use the SkyPilot VM Orchestrator if: * you want to maximize cost savings by leveraging spot VMs and auto-picking the cheapest VM/zone/region/cloud. * you want to ensure high GPU availability by provisioning VMs in all zones/regions/clouds you have access to. * you don't need a built-in UI of the orchestrator. (You can still use ZenML's Dashboard to view and monitor your pipelines/artifacts.) * you're not willing to maintain Kubernetes-based solutions or pay for managed solutions like [Sagemaker](sagemaker.md). ## How it works The orchestrator leverages the SkyPilot framework to handle the provisioning and scaling of VMs. It automatically manages the process of launching VMs for your pipelines, with support for both on-demand and managed spot VMs. While you can select the VM type you want to use, the orchestrator also includes an optimizer that automatically selects the cheapest VM/zone/region/cloud for your workloads. Finally, the orchestrator includes an autostop feature that cleans up idle clusters, preventing unnecessary cloud costs. {% hint style="info" %} You can configure the SkyPilot VM Orchestrator to use a specific VM type, and resources for each step of your pipeline can be configured individually. Read more about how to configure step-specific resources [here](skypilot-vm.md#configuring-step-specific-resources). {% endhint %} {% hint style="warning" %} The SkyPilot VM Orchestrator does not currently support the ability to [schedule pipelines runs](../../how-to/pipeline-development/build-pipelines/schedule-a-pipeline.md) {% endhint %} {% hint style="info" %} All ZenML pipeline runs are executed using Docker containers within the VMs provisioned by the orchestrator. For that reason, you may need to configure your pipeline settings with `docker_run_args=["--gpus=all"]` to enable GPU support in the Docker container. {% endhint %} ## How to deploy it You don't need to do anything special to deploy the SkyPilot VM Orchestrator. As the SkyPilot integration itself takes care of provisioning VMs, you can simply use the orchestrator as you would any other ZenML orchestrator. However, you will need to ensure that you have the appropriate permissions to provision VMs on your cloud provider of choice and to configure your SkyPilot orchestrator accordingly using the [service connectors](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) feature. {% hint style="info" %} The SkyPilot VM Orchestrator currently only supports the AWS, GCP, and Azure cloud platforms. {% endhint %} ## How to use it To use the SkyPilot VM Orchestrator, you need: * One of the SkyPilot integrations installed. You can install the SkyPilot integration for your cloud provider of choice using the following command: ```shell # For AWS pip install "zenml[connectors-aws]" zenml integration install aws skypilot_aws # for GCP pip install "zenml[connectors-gcp]" zenml integration install gcp skypilot_gcp # for GCP # for Azure pip install "zenml[connectors-azure]" zenml integration install azure skypilot_azure # for Azure ``` * [Docker](https://www.docker.com) installed and running. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. * A [remote container registry](../container-registries/container-registries.md) as part of your stack. * A [remote ZenML deployment](../../getting-started/deploying-zenml/README.md). * The appropriate permissions to provision VMs on your cloud provider of choice. * A [service connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) configured to authenticate with your cloud provider of choice. {% tabs %} {% tab title="AWS" %} We need first to install the SkyPilot integration for AWS and the AWS connectors extra, using the following two commands: ```shell pip install "zenml[connectors-aws]" zenml integration install aws skypilot_aws ``` To provision VMs on AWS, your VM Orchestrator stack component needs to be configured to authenticate with [AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md). To configure the AWS Service Connector, you need to register a new service connector configured with AWS credentials that have at least the minimum permissions required by SkyPilot as documented [here](https://skypilot.readthedocs.io/en/latest/cloud-setup/cloud-permissions/aws.html). First, check that the AWS service connector type is available using the following command: ```shell zenml service-connector list-types --type aws ``` ```shell ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ NAME β”‚ TYPE β”‚ RESOURCE TYPES β”‚ AUTH METHODS β”‚ LOCAL β”‚ REMOTE ┃ ┠───────────────────────┼────────┼───────────────────────┼──────────────────┼───────┼────────┨ ┃ AWS Service Connector β”‚ πŸ”Ά aws β”‚ πŸ”Ά aws-generic β”‚ implicit β”‚ βœ… β”‚ βž– ┃ ┃ β”‚ β”‚ πŸ“¦ s3-bucket β”‚ secret-key β”‚ β”‚ ┃ ┃ β”‚ β”‚ πŸŒ€ kubernetes-cluster β”‚ sts-token β”‚ β”‚ ┃ ┃ β”‚ β”‚ 🐳 docker-registry β”‚ iam-role β”‚ β”‚ ┃ ┃ β”‚ β”‚ β”‚ session-token β”‚ β”‚ ┃ ┃ β”‚ β”‚ β”‚ federation-token β”‚ β”‚ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` Next, configure a service connector using the CLI or the dashboard with the AWS credentials. For example, the following command uses the local AWS CLI credentials to auto-configure the service connector: ```shell zenml service-connector register aws-skypilot-vm --type aws --region=us-east-1 --auto-configure ``` This will automatically configure the service connector with the appropriate credentials and permissions to provision VMs on AWS. You can then use the service connector to configure your registered VM Orchestrator stack component using the following command: ```shell # Register the orchestrator zenml orchestrator register --flavor vm_aws # Connect the orchestrator to the service connector zenml orchestrator connect --connector aws-skypilot-vm # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` {% endtab %} {% tab title="GCP" %} We need first to install the SkyPilot integration for GCP and the GCP extra for ZenML, using the following two commands: ```shell pip install "zenml[connectors-gcp]" zenml integration install gcp skypilot_gcp ``` To provision VMs on GCP, your VM Orchestrator stack component needs to be configured to authenticate with [GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) To configure the GCP Service Connector, you need to register a new service connector, but first let's check the available service connectors types using the following command: ```shell zenml service-connector list-types --type gcp ``` ```shell ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ NAME β”‚ TYPE β”‚ RESOURCE TYPES β”‚ AUTH METHODS β”‚ LOCAL β”‚ REMOTE ┃ ┠───────────────────────┼────────┼───────────────────────┼─────────────────┼───────┼────────┨ ┃ GCP Service Connector β”‚ πŸ”΅ gcp β”‚ πŸ”΅ gcp-generic β”‚ implicit β”‚ βœ… β”‚ βž– ┃ ┃ β”‚ β”‚ πŸ“¦ gcs-bucket β”‚ user-account β”‚ β”‚ ┃ ┃ β”‚ β”‚ πŸŒ€ kubernetes-cluster β”‚ service-account β”‚ β”‚ ┃ ┃ β”‚ β”‚ 🐳 docker-registry β”‚ oauth2-token β”‚ β”‚ ┃ ┃ β”‚ β”‚ β”‚ impersonation β”‚ β”‚ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` For this example we will configure a service connector using the `user-account` auth method. But before we can do that, we need to login to GCP using the following command: ```shell gcloud auth application-default login ``` This will open a browser window and ask you to login to your GCP account. Once you have logged in, you can register a new service connector using the following command: ```shell # We want to use --auto-configure to automatically configure the service connector with the appropriate credentials and permissions to provision VMs on GCP. zenml service-connector register gcp-skypilot-vm -t gcp --auth-method user-account --auto-configure # using generic resource type requires disabling the generation of temporary tokens zenml service-connector update gcp-skypilot-vm --generate_temporary_tokens=False ``` This will automatically configure the service connector with the appropriate credentials and permissions to provision VMs on GCP. You can then use the service connector to configure your registered VM Orchestrator stack component using the following commands: ```shell # Register the orchestrator zenml orchestrator register --flavor vm_gcp # Connect the orchestrator to the service connector zenml orchestrator connect --connector gcp-skypilot-vm # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` {% endtab %} {% tab title="Azure" %} We need first to install the SkyPilot integration for Azure and the Azure extra for ZenML, using the following two commands ```shell pip install "zenml[connectors-azure]" zenml integration install azure skypilot_azure ``` To provision VMs on Azure, your VM Orchestrator stack component needs to be configured to authenticate with [Azure Service Connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md) To configure the Azure Service Connector, you need to register a new service connector, but first let's check the available service connectors types using the following command: ```shell zenml service-connector list-types --type azure ``` ```shell ┏━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ NAME β”‚ TYPE β”‚ RESOURCE TYPES β”‚ AUTH METHODS β”‚ LOCAL β”‚ REMOTE ┃ ┠─────────────────────────┼───────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ Azure Service Connector β”‚ πŸ‡¦ azure β”‚ πŸ‡¦ azure-generic β”‚ implicit β”‚ βœ… β”‚ βž– ┃ ┃ β”‚ β”‚ πŸ“¦ blob-container β”‚ service-principal β”‚ β”‚ ┃ ┃ β”‚ β”‚ πŸŒ€ kubernetes-cluster β”‚ access-token β”‚ β”‚ ┃ ┃ β”‚ β”‚ 🐳 docker-registry β”‚ β”‚ β”‚ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ zenml service-connector register azure-skypilot-vm -t azure --auth-method access-token --auto-configure ``` This will automatically configure the service connector with the appropriate credentials and permissions to provision VMs on Azure. You can then use the service connector to configure your registered VM Orchestrator stack component using the following commands: ```shell # Register the orchestrator zenml orchestrator register --flavor vm_azure # Connect the orchestrator to the service connector zenml orchestrator connect --connector azure-skypilot-vm # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` {% endtab %} {% tab title="Lambda Labs" %} [Lambda Labs](https://lambdalabs.com/service/gpu-cloud) is a cloud provider that offers GPU instances for machine learning workloads. Unlike the major cloud providers, with Lambda Labs we don't need to configure a service connector to authenticate with the cloud provider. Instead, we can directly use API keys to authenticate with the Lambda Labs API. ```shell zenml integration install skypilot_lambda ``` Once the integration is installed, we can register the orchestrator with the following command: ```shell # For more secure and recommended way, we will register the API key as a secret zenml secret create lambda_api_key --scope user --api_key= # Register the orchestrator zenml orchestrator register --flavor vm_lambda --api_key={{lambda_api_key.api_key}} # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` {% hint style="info" %} The Lambda Labs orchestrator does not support some of the features like `job_recovery`, `disk_tier`, `image_id`, `zone`, `idle_minutes_to_autostop`, `disk_size`, `use_spot`. It is recommended not to use these features with the Lambda Labs orchestrator and not to use [step-specific settings](skypilot-vm.md#configuring-step-specific-resources). {% endhint %} {% hint style="warning" %} While testing the orchestrator, we noticed that the Lambda Labs orchestrator does not support the `down` flag. This means the orchestrator will not automatically tear down the cluster after all jobs finish. We recommend manually tearing down the cluster after all jobs finish to avoid unnecessary costs. {% endhint %} {% endtab %} {% tab title="Kubernetes" %} We need first to install the SkyPilot integration for Kubernetes, using the following two commands: ```shell zenml integration install skypilot_kubernetes ``` To provision skypilot on kubernetes cluster, your orchestrator stack components needs to be configured to authenticate with a [Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md). To configure the Service Connector, you need to register a new service connector configured with the appropriate credentials and permissions to access the K8s cluster. You can then use the service connector to configure your registered the Orchestrator stack component using the following command: First, check that the Kubernetes service connector type is available using the following command: ```shell zenml service-connector list-types --type kubernetes ``` ```shell ┏━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ β”‚ β”‚ RESOURCE β”‚ AUTH β”‚ β”‚ ┃ ┃ NAME β”‚ TYPE β”‚ TYPES β”‚ METHODS β”‚ LOCAL β”‚ REMOTE ┃ ┠────────────┼────────────┼────────────┼───────────┼───────┼────────┨ ┃ Kubernetes β”‚ πŸŒ€ β”‚ πŸŒ€ β”‚ password β”‚ βœ… β”‚ βœ… ┃ ┃ Service β”‚ kubernetes β”‚ kubernetes β”‚ token β”‚ β”‚ ┃ ┃ Connector β”‚ β”‚ -cluster β”‚ β”‚ β”‚ ┃ ┗━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` Next, configure a service connector using the CLI or the dashboard with the AWS credentials. For example, the following command uses the local AWS CLI credentials to auto-configure the service connector: ```shell zenml service-connector register kubernetes-skypilot --type kubernetes -i ``` This will automatically configure the service connector with the appropriate credentials and permissions to provision VMs on AWS. You can then use the service connector to configure your registered VM Orchestrator stack component using the following command: ```shell # Register the orchestrator zenml orchestrator register --flavor sky_kubernetes # Connect the orchestrator to the service connector zenml orchestrator connect --connector kubernetes-skypilot # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` {% hint style="warning" %} Some of the features like `job_recovery`, `disk_tier`, `image_id`, `zone`, `idle_minutes_to_autostop`, `disk_size`, `use_spot` are not supported by the Kubernetes orchestrator. It is recommended not to use these features with the Kubernetes orchestrator and not to use [step-specific settings](skypilot-vm.md#configuring-step-specific-resources). {% endhint %} {% endtab %} {% endtabs %} #### Additional Configuration For additional configuration of the Skypilot orchestrator, you can pass `Settings` depending on which cloud you are using which allows you to configure (among others) the following attributes: * `instance_type`: The instance type to use. * `cpus`: The number of CPUs required for the task. If a string, must be a string of the form `'2'` or `'2+'`, where the `+` indicates that the task requires at least 2 CPUs. * `memory`: The amount of memory in GiB required. If a string, must be a string of the form `'16'` or `'16+'`, where the `+` indicates that the task requires at least 16 GB of memory. * `accelerators`: The accelerators required. If a string, must be a string of the form `'V100'` or `'V100:2'`, where the `:2` indicates that the task requires 2 V100 GPUs. If a dict, must be a dict of the form `{'V100': 2}` or `{'tpu-v2-8': 1}`. * `accelerator_args`: Accelerator-specific arguments. For example, `{'tpu_vm': True, 'runtime_version': 'tpu-vm-base'}` for TPUs. * `use_spot`: Whether to use spot instances. If None, defaults to False. * `job_recovery`: The spot recovery strategy to use for the managed spot to recover the cluster from preemption. Read more about the available strategies [here](https://skypilot.readthedocs.io/en/latest/reference/api.html?highlight=instance\_type#resources) * `region`: The cloud region to use. * `zone`: The cloud zone to use within the region. * `image_id`: The image ID to use. If a string, must be a string of the image id from the cloud, such as AWS: `'ami-1234567890abcdef0'`, GCP: `'projects/my-project-id/global/images/my-image-name'`; Or, a image tag provided by SkyPilot, such as AWS: `'skypilot:gpu-ubuntu-2004'`. If a dict, must be a dict mapping from region to image ID. * `disk_size`: The size of the OS disk in GiB. * `disk_tier`: The disk performance tier to use. If None, defaults to `'medium'`. * `cluster_name`: Name of the cluster to create/reuse. If None, auto-generate a name. SkyPilot uses term `cluster` to refer to a group or a single VM that are provisioned to execute the task. The cluster name is used to identify the cluster and to determine whether to reuse an existing cluster or create a new one. * `retry_until_up`: Whether to retry launching the cluster until it is up. * `idle_minutes_to_autostop`: Automatically stop the cluster after this many minutes of idleness, i.e., no running or pending jobs in the cluster's job queue. Idleness gets reset whenever setting-up/running/pending jobs are found in the job queue. Setting this flag is equivalent to running `sky.launch(..., detach_run=True, ...)` and then `sky.autostop(idle_minutes=)`. If not set, the cluster will not be autostopped. * `down`: Tear down the cluster after all jobs finish (successfully or abnormally). If `idle_minutes_to_autostop` is also set, the cluster will be torn down after the specified idle time. Note that if errors occur during provisioning/data syncing/setting up, the cluster will not be torn down for debugging purposes. * `stream_logs`: If True, show the logs in the terminal as they are generated while the cluster is running. * `docker_run_args`: Additional arguments to pass to the `docker run` command. For example, `['--gpus=all']` to use all GPUs available on the VM. The following code snippets show how to configure the orchestrator settings for each cloud provider: {% tabs %} {% tab title="AWS" %} **Code Example:** ```python from zenml.integrations.skypilot_aws.flavors.skypilot_orchestrator_aws_vm_flavor import SkypilotAWSOrchestratorSettings skypilot_settings = SkypilotAWSOrchestratorSettings( cpus="2", memory="16", accelerators="V100:2", accelerator_args={"tpu_vm": True, "runtime_version": "tpu-vm-base"}, use_spot=True, job_recovery="recovery_strategy", region="us-west-1", zone="us-west1-a", image_id="ami-1234567890abcdef0", disk_size=100, disk_tier="high", cluster_name="my_cluster", retry_until_up=True, idle_minutes_to_autostop=60, down=True, stream_logs=True docker_run_args=["--gpus=all"] ) @pipeline( settings={ "orchestrator": skypilot_settings } ) ``` {% endtab %} {% tab title="GCP" %} **Code Example:** ```python from zenml.integrations.skypilot_gcp.flavors.skypilot_orchestrator_gcp_vm_flavor import SkypilotGCPOrchestratorSettings skypilot_settings = SkypilotGCPOrchestratorSettings( cpus="2", memory="16", accelerators="V100:2", accelerator_args={"tpu_vm": True, "runtime_version": "tpu-vm-base"}, use_spot=True, job_recovery="recovery_strategy", region="us-west1", zone="us-west1-a", image_id="ubuntu-pro-2004-focal-v20231101", disk_size=100, disk_tier="high", cluster_name="my_cluster", retry_until_up=True, idle_minutes_to_autostop=60, down=True, stream_logs=True ) @pipeline( settings={ "orchestrator": skypilot_settings } ) ``` {% endtab %} {% tab title="Azure" %} **Code Example:** ```python from zenml.integrations.skypilot_azure.flavors.skypilot_orchestrator_azure_vm_flavor import SkypilotAzureOrchestratorSettings skypilot_settings = SkypilotAzureOrchestratorSettings( cpus="2", memory="16", accelerators="V100:2", accelerator_args={"tpu_vm": True, "runtime_version": "tpu-vm-base"}, use_spot=True, job_recovery="recovery_strategy", region="West Europe", image_id="Canonical:0001-com-ubuntu-server-jammy:22_04-lts-gen2:latest", disk_size=100, disk_tier="high", cluster_name="my_cluster", retry_until_up=True, idle_minutes_to_autostop=60, down=True, stream_logs=True ) @pipeline( settings={ "orchestrator": skypilot_settings } ) ``` {% endtab %} {% tab title="Lambda" %} **Code Example:** ```python from zenml.integrations.skypilot_lambda import SkypilotLambdaOrchestratorSettings skypilot_settings = SkypilotLambdaOrchestratorSettings( instance_type="gpu_1x_h100_pcie", cluster_name="my_cluster", retry_until_up=True, idle_minutes_to_autostop=60, down=True, stream_logs=True, docker_run_args=["--gpus=all"] ) @pipeline( settings={ "orchestrator": skypilot_settings } ) ``` {% endtab %} {% tab title="Kubernetes" %} **Code Example:** ```python from zenml.integrations.skypilot_kubernetes.flavors.skypilot_orchestrator_kubernetes_vm_flavor import SkypilotKubernetesOrchestratorSettings skypilot_settings = SkypilotKubernetesOrchestratorSettings( cpus="2", memory="16", accelerators="V100:2", image_id="ami-1234567890abcdef0", disk_size=100, cluster_name="my_cluster", retry_until_up=True, stream_logs=True docker_run_args=["--gpus=all"] ) @pipeline( settings={ "orchestrator": skypilot_settings } ) ``` {% endtab %} {% endtabs %} One of the key features of the SkyPilot VM Orchestrator is the ability to run each step of a pipeline on a separate VM with its own specific settings. This allows for fine-grained control over the resources allocated to each step, ensuring that each part of your pipeline has the necessary compute power while optimizing for cost and efficiency. ## Configuring Step-Specific Resources The SkyPilot VM Orchestrator allows you to configure resources for each step individually. This means you can specify different VM types, CPU and memory requirements, and even use spot instances for certain steps while using on-demand instances for others. If no step-specific settings are specified, the orchestrator will use the resources specified in the orchestrator settings for each step and run the entire pipeline in one VM. If step-specific settings are specified, an orchestrator VM will be spun up first, which will subsequently spin out new VMs dependent on the step settings. You can disable this behavior by setting the `disable_step_based_settings` parameter to `True` in the orchestrator configuration, using the following command: ```shell zenml orchestrator update --disable_step_based_settings=True ``` Here's an example of how to configure specific resources for a step for the AWS cloud: ```python from zenml.integrations.skypilot_aws.flavors.skypilot_orchestrator_aws_vm_flavor import SkypilotAWSOrchestratorSettings # Settings for a specific step that requires more resources high_resource_settings = SkypilotAWSOrchestratorSettings( instance_type='t2.2xlarge', cpus=8, memory=32, use_spot=False, region='us-east-1', # ... other settings ) @step(settings={"orchestrator": high_resource_settings}) def my_resource_intensive_step(): # Step implementation pass ``` {% hint style="warning" %} When configuring pipeline or step-specific resources, you can use the `settings` parameter to specifically target the orchestrator flavor you want to use `orchestrator.STACK_COMPONENT_FLAVOR` and not orchestrator component name `orchestrator.STACK_COMPONENT_NAME`. For example, if you want to configure resources for the `vm_gcp` flavor, you can use `settings={"orchestrator": ...}`. {% endhint %} By using the `settings` parameter, you can tailor the resources for each step according to its specific needs. This flexibility allows you to optimize your pipeline execution for both performance and cost. Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-skypilot/#zenml.integrations.skypilot.flavors.skypilot\_orchestrator\_base\_vm\_flavor.SkypilotBaseOrchestratorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings.
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/tekton.md ================ --- description: Orchestrating your pipelines to run on Tekton. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Tekton Orchestrator [Tekton](https://tekton.dev/) is a powerful and flexible open-source framework for creating CI/CD systems, allowing developers to build, test, and deploy across cloud providers and on-premise systems. {% hint style="warning" %} This component is only meant to be used within the context of a [remote ZenML deployment scenario](../../getting-started/deploying-zenml/README.md). Usage with a local ZenML deployment may lead to unexpected behavior! {% endhint %} ### When to use it You should use the Tekton orchestrator if: * you're looking for a proven production-grade orchestrator. * you're looking for a UI in which you can track your pipeline runs. * you're already using Kubernetes or are not afraid of setting up and maintaining a Kubernetes cluster. * you're willing to deploy and maintain Tekton Pipelines on your cluster. ### How to deploy it You'll first need to set up a Kubernetes cluster and deploy Tekton Pipelines: {% tabs %} {% tab title="AWS" %} * A remote ZenML server. See the [deployment guide](../../getting-started/deploying-zenml/README.md) for more information. * Have an existing AWS [EKS cluster](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html) set up. * Make sure you have the [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) set up. * Download and [install](https://kubernetes.io/docs/tasks/tools/) `kubectl` and [configure](https://aws.amazon.com/premiumsupport/knowledge-center/eks-cluster-connection/) it to talk to your EKS cluster using the following command: ```powershell aws eks --region REGION update-kubeconfig --name CLUSTER_NAME ``` * [Install](https://tekton.dev/docs/pipelines/install/) Tekton Pipelines onto your cluster. {% endtab %} {% tab title="GCP" %} * A remote ZenML server. See the [deployment guide](../../getting-started/deploying-zenml/README.md) for more information. * Have an existing GCP [GKE cluster](https://cloud.google.com/kubernetes-engine/docs/quickstart) set up. * Make sure you have the [Google Cloud CLI](https://cloud.google.com/sdk/docs/install-sdk) set up first. * Download and [install](https://kubernetes.io/docs/tasks/tools/) `kubectl` and [configure](https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl) it to talk to your GKE cluster using the following command: ```powershell gcloud container clusters get-credentials CLUSTER_NAME ``` * [Install](https://tekton.dev/docs/pipelines/install/) Tekton Pipelines onto your cluster. {% endtab %} {% tab title="Azure" %} * A remote ZenML server. See the [deployment guide](../../getting-started/deploying-zenml/README.md) for more information. * Have an existing [AKS cluster](https://azure.microsoft.com/en-in/services/kubernetes-service/#documentation) set up. * Make sure you have the [`az` CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli) set up first. * Download and [install](https://kubernetes.io/docs/tasks/tools/) `kubectl` and it to talk to your AKS cluster using the following command: ```powershell az aks get-credentials --resource-group RESOURCE_GROUP --name CLUSTER_NAME ``` * [Install](https://tekton.dev/docs/pipelines/install/) Tekton Pipelines onto your cluster. {% endtab %} {% endtabs %} {% hint style="info" %} If one or more of the deployments are not in the `Running` state, try increasing the number of nodes in your cluster. {% endhint %} {% hint style="warning" %} ZenML has only been tested with Tekton Pipelines >=0.38.3 and may not work with previous versions. {% endhint %} ### How to use it To use the Tekton orchestrator, we need: * The ZenML `tekton` integration installed. If you haven't done so, run ```shell zenml integration install tekton -y ``` * [Docker](https://www.docker.com) installed and running. * Tekton pipelines deployed on a remote cluster. See the [deployment section](tekton.md#how-to-deploy-it) for more information. * The name of your Kubernetes context which points to your remote cluster. Run `kubectl config get-contexts` to see a list of available contexts. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. * A [remote container registry](../container-registries/container-registries.md) as part of your stack. * [kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl) installed and the name of the Kubernetes configuration context which points to the target cluster (i.e. run`kubectl config get-contexts` to see a list of available contexts). This is optional (see below). {% hint style="info" %} It is recommended that you set up [a Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) and use it to connect ZenML Stack Components to the remote Kubernetes cluster, especially If you are using a Kubernetes cluster managed by a cloud provider like AWS, GCP or Azure, This guarantees that your Stack is fully portable on other environments and your pipelines are fully reproducible. {% endhint %} We can then register the orchestrator and use it in our active stack. This can be done in two ways: 1. If you have [a Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) configured to access the remote Kubernetes cluster, you no longer need to set the `kubernetes_context` attribute to a local `kubectl` context. In fact, you don't need the local Kubernetes CLI at all. You can [connect the stack component to the Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md#connect-stack-components-to-resources) instead: ``` $ zenml orchestrator register --flavor tekton Running with active stack: 'default' (repository) Successfully registered orchestrator ``. $ zenml service-connector list-resources --resource-type kubernetes-cluster -e The following 'kubernetes-cluster' resources can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ e33c9fac-5daa-48b2-87bb-0187d3782cde β”‚ aws-iam-multi-eu β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ kubeflowmultitenant ┃ ┃ β”‚ β”‚ β”‚ β”‚ zenbox ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ ed528d5a-d6cb-4fc4-bc52-c3d2d01643e5 β”‚ aws-iam-multi-us β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ zenhacks-cluster ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ 1c54b32a-4889-4417-abbd-42d3ace3d03a β”‚ gcp-sa-multi β”‚ πŸ”΅ gcp β”‚ πŸŒ€ kubernetes-cluster β”‚ zenml-test-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┛ $ zenml orchestrator connect --connector aws-iam-multi-us Running with active stack: 'default' (repository) Successfully connected orchestrator `` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼──────────────────┼────────────────┼───────────────────────┼──────────────────┨ ┃ ed528d5a-d6cb-4fc4-bc52-c3d2d01643e5 β”‚ aws-iam-multi-us β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ zenhacks-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┛ # Register and activate a stack with the new orchestrator $ zenml stack register -o ... --set ``` 2. if you don't have a Service Connector on hand and you don't want to [register one](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md#register-service-connectors) , the local Kubernetes `kubectl` client needs to be configured with a configuration context pointing to the remote cluster. The `kubernetes_context` stack component must also be configured with the value of that context: ```shell zenml orchestrator register \ --flavor=tekton \ --kubernetes_context= # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` {% hint style="info" %} ZenML will build a Docker image called `/zenml:` which includes your code and use it to run your pipeline steps in Tekton. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. {% endhint %} You can now run any ZenML pipeline using the Tekton orchestrator: ```shell python file_that_runs_a_zenml_pipeline.py ``` #### Tekton UI Tekton comes with its own UI that you can use to find further details about your pipeline runs, such as the logs of your steps. ![Tekton UI](../../.gitbook/assets/TektonUI.png) To find the Tekton UI endpoint, we can use the following command: ```bash kubectl get ingress -n tekton-pipelines -o jsonpath='{.items[0].spec.rules[0].host}' ``` #### Additional configuration For additional configuration of the Tekton orchestrator, you can pass `TektonOrchestratorSettings` which allows you to configure node selectors, affinity, and tolerations to apply to the Kubernetes Pods running your pipeline. These can be either specified using the Kubernetes model objects or as dictionaries. ```python from zenml.integrations.tekton.flavors.tekton_orchestrator_flavor import TektonOrchestratorSettings from kubernetes.client.models import V1Toleration tekton_settings = TektonOrchestratorSettings( pod_settings={ "affinity": { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [ { "matchExpressions": [ { "key": "node.kubernetes.io/name", "operator": "In", "values": ["my_powerful_node_group"], } ] } ] } } }, "tolerations": [ V1Toleration( key="node.kubernetes.io/name", operator="Equal", value="", effect="NoSchedule" ) ] } ) ``` If your pipelines steps have certain hardware requirements, you can specify them as `ResourceSettings`: ```python resource_settings = ResourceSettings(cpu_count=8, memory="16GB") ``` These settings can then be specified on either pipeline-level or step-level: ```python # Either specify on pipeline-level @pipeline( settings={ "orchestrator": tekton_settings, "resources": resource_settings, } ) def my_pipeline(): ... # OR specify settings on step-level @step( settings={ "orchestrator": tekton_settings, "resources": resource_settings, } ) def my_step(): ... ``` Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-tekton/#zenml.integrations.tekton.flavors.tekton\_orchestrator\_flavor.TektonOrchestratorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings. For more information and a full list of configurable attributes of the Tekton orchestrator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-tekton/#zenml.integrations.tekton.orchestrators.tekton\_orchestrator.TektonOrchestrator) . #### Enabling CUDA for GPU-backed hardware Note that if you wish to use this orchestrator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/orchestrators/vertex.md ================ --- description: Orchestrating your pipelines to run on Vertex AI. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Google Cloud VertexAI Orchestrator [Vertex AI Pipelines](https://cloud.google.com/vertex-ai/docs/pipelines/introduction) is a serverless ML workflow tool running on the Google Cloud Platform. It is an easy way to quickly run your code in a production-ready, repeatable cloud orchestrator that requires minimal setup without provisioning and paying for standby compute. {% hint style="warning" %} This component is only meant to be used within the context of a [remote ZenML deployment scenario](../../getting-started/deploying-zenml/README.md). Usage with a local ZenML deployment may lead to unexpected behavior! {% endhint %} ## When to use it You should use the Vertex orchestrator if: * you're already using GCP. * you're looking for a proven production-grade orchestrator. * you're looking for a UI in which you can track your pipeline runs. * you're looking for a managed solution for running your pipelines. * you're looking for a serverless solution for running your pipelines. ## How to deploy it {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including a Vertex AI orchestrator? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), the [stack registration wizard](../../how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md), or [the ZenML GCP Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} In order to use a Vertex AI orchestrator, you need to first deploy [ZenML to the cloud](../../getting-started/deploying-zenml/README.md). It would be recommended to deploy ZenML in the same Google Cloud project as where the Vertex infrastructure is deployed, but it is not necessary to do so. You must ensure that you are connected to the remote ZenML server before using this stack component. The only other thing necessary to use the ZenML Vertex orchestrator is enabling Vertex-relevant APIs on the Google Cloud project. ## How to use it To use the Vertex orchestrator, we need: * The ZenML `gcp` integration installed. If you haven't done so, run ```shell zenml integration install gcp ``` * [Docker](https://www.docker.com) installed and running. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. * A [remote container registry](../container-registries/container-registries.md) as part of your stack. * [GCP credentials with proper permissions](vertex.md#gcp-credentials-and-permissions) * The GCP project ID and location in which you want to run your Vertex AI pipelines. ### GCP credentials and permissions This part is without doubt the most involved part of using the Vertex orchestrator. In order to run pipelines on Vertex AI, you need to have a GCP user account and/or one or more GCP service accounts set up with proper permissions, depending on whether you wish to practice [the principle of least privilege](https://en.wikipedia.org/wiki/Principle\_of\_least\_privilege) and distribute permissions across multiple service accounts. You also have three different options to provide credentials to the orchestrator: * use the [`gcloud` CLI](https://cloud.google.com/sdk/gcloud) to authenticate locally with GCP * configure the orchestrator to use a [service account key file](https://cloud.google.com/iam/docs/creating-managing-service-account-keys) to authenticate with GCP by setting the `service_account_path` parameter in the orchestrator configuration. * (recommended) configure [a GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) with GCP credentials and then link the Vertex AI Orchestrator stack component to the Service Connector. This section [explains the different components and GCP resources](vertex.md#vertex-ai-pipeline-components) involved in running a Vertex AI pipeline and what permissions they need, then provides instructions for three different configuration use-cases: 1. [use the local `gcloud` CLI configured with your GCP user account](vertex.md#configuration-use-case-local-gcloud-cli-with-user-account), including the ability to schedule pipelines 2. [use a GCP Service Connector and a single service account](vertex.md#configuration-use-case-gcp-service-connector-with-single-service-account) with all permissions, including the ability to schedule pipelines 3. [use a GCP Service Connector and multiple service accounts](vertex.md#configuration-use-case-gcp-service-connector-with-different-service-accounts) for different permissions, including the ability to schedule pipelines #### Vertex AI pipeline components To understand what accounts you need to provision and why, let's look at the different components of the Vertex orchestrator: 1. _the ZenML client environment_ is the environment where you run the ZenML code responsible for building the pipeline Docker image and submitting the pipeline to Vertex AI, among other things. This is usually your local machine or some other environment used to automate running pipelines, like a CI/CD job. This environment needs to be able to authenticate with GCP and needs to have the necessary permissions to create a job in Vertex Pipelines, (e.g. [the `Vertex AI User` role](https://cloud.google.com/vertex-ai/docs/general/access-control#aiplatform.user)). If you are planning to [run pipelines on a schedule](vertex.md#run-pipelines-on-a-schedule), _the ZenML client environment_ also needs additional permissions: * the [`Storage Object Creator Role`](https://cloud.google.com/iam/docs/understanding-roles#storage.objectCreator) to be able to write the pipeline JSON file to the artifact store directly (NOTE: not needed if the Artifact Store is configured with credentials or is linked to Service Connector) 2. _the Vertex AI pipeline environment_ is the GCP environment in which the pipeline steps themselves are running in GCP. The Vertex AI pipeline runs in the context of a GCP service account which we'll call here _the workload service account_. _The workload service account_ can be explicitly configured in the orchestrator configuration via the `workload_service_account` parameter. If it is omitted, the orchestrator will use [the Compute Engine default service account](https://cloud.google.com/compute/docs/access/service-accounts#default\_service\_account) for the GCP project in which the pipeline is running. This service account needs to have the following permissions: * permissions to run a Vertex AI pipeline, (e.g. [the `Vertex AI Service Agent` role](https://cloud.google.com/vertex-ai/docs/general/access-control#aiplatform.serviceAgent)). As you can see, there can be dedicated service accounts involved in running a Vertex AI pipeline. That's two service accounts if you also use a service account to authenticate to GCP in _the ZenML client environment_. However, you can keep it simple and use the same service account everywhere. #### Configuration use-case: local `gcloud` CLI with user account This configuration use-case assumes you have configured the [`gcloud` CLI](https://cloud.google.com/sdk/gcloud) to authenticate locally with your GCP account (i.e. by running `gcloud auth login`). It also assumes the following: * your GCP account has permissions to create a job in Vertex Pipelines, (e.g. [the `Vertex AI User` role](https://cloud.google.com/vertex-ai/docs/general/access-control#aiplatform.user)). * [the Compute Engine default service account](https://cloud.google.com/compute/docs/access/service-accounts#default\_service\_account) for the GCP project in which the pipeline is running is updated with additional permissions required to run a Vertex AI pipeline, (e.g. [the `Vertex AI Service Agent` role](https://cloud.google.com/vertex-ai/docs/general/access-control#aiplatform.serviceAgent)). This is the easiest way to configure the Vertex AI Orchestrator, but it has the following drawbacks: * the setup is not portable on other machines and reproducible by other users. * it uses the Compute Engine default service account, which is not recommended, given that it has a lot of permissions by default and is used by many other GCP services. We can then register the orchestrator as follows: ```shell zenml orchestrator register \ --flavor=vertex \ --project= \ --location= \ --synchronous=true ``` #### Configuration use-case: GCP Service Connector with single service account This use-case assumes you have already configured a GCP service account with the following permissions: * permissions to create a job in Vertex Pipelines, (e.g. [the `Vertex AI User` role](https://cloud.google.com/vertex-ai/docs/general/access-control#aiplatform.user)). * permissions to run a Vertex AI pipeline, (e.g. [the `Vertex AI Service Agent` role](https://cloud.google.com/vertex-ai/docs/general/access-control#aiplatform.serviceAgent)). * the [Storage Object Creator Role](https://cloud.google.com/iam/docs/understanding-roles#storage.objectCreator) to be able to write the pipeline JSON file to the artifact store directly. It also assumes you have already created a service account key for this service account and downloaded it to your local machine (e.g. in a `connectors-vertex-ai-workload.json` file). This is not recommended if you are conscious about security. The principle of least privilege is not applied here and the environment in which the pipeline steps are running has many permissions that it doesn't need. ```shell zenml service-connector register --type gcp --auth-method=service-account --project_id= --service_account_json=@connectors-vertex-ai-workload.json --resource-type gcp-generic zenml orchestrator register \ --flavor=vertex \ --location= \ --synchronous=true \ --workload_service_account=@.iam.gserviceaccount.com zenml orchestrator connect --connector ``` #### Configuration use-case: GCP Service Connector with different service accounts This setup applies the principle of least privilege by using different service accounts with the minimum of permissions needed for [the different components involved in running a Vertex AI pipeline](vertex.md#vertex-ai-pipeline-components). It also uses a GCP Service Connector to make the setup portable and reproducible. This configuration is a best-in-class setup that you would normally use in production, but it requires a lot more work to prepare. {% hint style="info" %} This setup involves creating and configuring several GCP service accounts, which is a lot of work and can be error prone. If you don't really need the added security, you can use [the GCP Service Connector with a single service account](vertex.md#configuration-use-case-gcp-service-connector-with-single-service-account) instead. {% endhint %} The following GCP service accounts are needed: 1. a "client" service account that has the following permissions: * permissions to create a job in Vertex Pipelines, (e.g. [the `Vertex AI User` role](https://cloud.google.com/vertex-ai/docs/general/access-control#aiplatform.user)). * permissions to create a Google Cloud Function (e.g. with the [`Cloud Functions Developer Role`](https://cloud.google.com/functions/docs/reference/iam/roles#cloudfunctions.developer)). * the [Storage Object Creator Role](https://cloud.google.com/iam/docs/understanding-roles#storage.objectCreator) to be able to write the pipeline JSON file to the artifact store directly (NOTE: not needed if the Artifact Store is configured with credentials or is linked to Service Connector). 2. a "workload" service account that has permissions to run a Vertex AI pipeline, (e.g. [the `Vertex AI Service Agent` role](https://cloud.google.com/vertex-ai/docs/general/access-control#aiplatform.serviceAgent)). A key is also needed for the "client" service account. You can create a key for this service account and download it to your local machine (e.g. in a `connectors-vertex-ai-workload.json` file). With all the service accounts and the key ready, we can register [the GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) and Vertex AI orchestrator as follows: ```shell zenml service-connector register --type gcp --auth-method=service-account --project_id= --service_account_json=@connectors-vertex-ai-workload.json --resource-type gcp-generic zenml orchestrator register \ --flavor=vertex \ --location= \ --synchronous=true \ --workload_service_account=@.iam.gserviceaccount.com zenml orchestrator connect --connector ``` ### Configuring the stack With the orchestrator registered, we can use it in our active stack: ```shell # Register and activate a stack with the new orchestrator zenml stack register -o ... --set ``` {% hint style="info" %} ZenML will build a Docker image called `/zenml:` which includes your code and use it to run your pipeline steps in Vertex AI. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. {% endhint %} You can now run any ZenML pipeline using the Vertex orchestrator: ```shell python file_that_runs_a_zenml_pipeline.py ``` ### Vertex UI Vertex comes with its own UI that you can use to find further details about your pipeline runs, such as the logs of your steps. ![Vertex UI](../../.gitbook/assets/VertexUI.png) For any runs executed on Vertex, you can get the URL to the Vertex UI in Python using the following code snippet: ```python from zenml.client import Client pipeline_run = Client().get_pipeline_run("") orchestrator_url = pipeline_run.run_metadata["orchestrator_url"].value ``` ### Run pipelines on a schedule The Vertex Pipelines orchestrator supports running pipelines on a schedule using its [native scheduling capability](https://cloud.google.com/vertex-ai/docs/pipelines/schedule-pipeline-run). **How to schedule a pipeline** ```python from zenml.config.schedule import Schedule # Run a pipeline every 5th minute pipeline_instance.run( schedule=Schedule( cron_expression="*/5 * * * *" ) ) # Run a pipeline every hour # starting in one day from now and ending in three days from now pipeline_instance.run( schedule=Schedule( cron_expression="0 * * * *" start_time=datetime.datetime.now() + datetime.timedelta(days=1), end_time=datetime.datetime.now() + datetime.timedelta(days=3), ) ) ``` {% hint style="warning" %} The Vertex orchestrator only supports the `cron_expression`, `start_time` (optional) and `end_time` (optional) parameters in the `Schedule` object, and will ignore all other parameters supplied to define the schedule. {% endhint %} The `start_time` and `end_time` timestamp parameters are both optional and are to be specified in local time. They define the time window in which the pipeline runs will be triggered. If they are not specified, the pipeline will run indefinitely. The `cron_expression` parameter [supports timezones](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.schedules). For example, the expression `TZ=Europe/Paris 0 10 * * *` will trigger runs at 10:00 in the Europe/Paris timezone. **How to delete a scheduled pipeline** Note that ZenML only gets involved to schedule a run, but maintaining the lifecycle of the schedule is the responsibility of the user. In order to cancel a scheduled Vertex pipeline, you need to manually delete the schedule in VertexAI (via the UI or the CLI). ### Additional configuration For additional configuration of the Vertex orchestrator, you can pass `VertexOrchestratorSettings` which allows you to configure labels for your Vertex Pipeline jobs or specify which GPU to use. ```python from zenml.integrations.gcp.flavors.vertex_orchestrator_flavor import VertexOrchestratorSettings from kubernetes.client.models import V1Toleration vertex_settings = VertexOrchestratorSettings( labels={"key": "value"} ) ``` If your pipelines steps have certain hardware requirements, you can specify them as `ResourceSettings`: ```python resource_settings = ResourceSettings(cpu_count=8, memory="16GB") ``` To run your pipeline (or some steps of it) on a GPU, you will need to set both a node selector and the gpu count as follows: ```python vertex_settings = VertexOrchestratorSettings( pod_settings={ "node_selectors": { "cloud.google.com/gke-accelerator": "NVIDIA_TESLA_A100" }, } ) resource_settings = ResourceSettings(gpu_count=1) ``` You can find available accelerator types [here](https://cloud.google.com/vertex-ai/docs/training/configure-compute#specifying_gpus). These settings can then be specified on either pipeline-level or step-level: ```python # Either specify on pipeline-level @pipeline( settings={ "orchestrator": vertex_settings, "resources": resource_settings, } ) def my_pipeline(): ... # OR specify settings on step-level @step( settings={ "orchestrator": vertex_settings, "resources": resource_settings, } ) def my_step(): ... ``` Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-gcp/#zenml.integrations.gcp.flavors.vertex\_orchestrator\_flavor.VertexOrchestratorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings. For more information and a full list of configurable attributes of the Vertex orchestrator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-gcp/#zenml.integrations.gcp.orchestrators.vertex\_orchestrator.VertexOrchestrator) . ### Enabling CUDA for GPU-backed hardware Note that if you wish to use this orchestrator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/step-operators/azureml.md ================ --- description: Executing individual steps in AzureML. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # AzureML [AzureML](https://azure.microsoft.com/en-us/products/machine-learning/) offers specialized compute instances to run your training jobs and has a comprehensive UI to track and manage your models and logs. ZenML's AzureML step operator allows you to submit individual steps to be run on AzureML compute instances. ### When to use it You should use the AzureML step operator if: * one or more steps of your pipeline require computing resources (CPU, GPU, memory) that are not provided by your orchestrator. * you have access to AzureML. If you're using a different cloud provider, take a look at the [SageMaker](sagemaker.md) or [Vertex](vertex.md) step operators. ### How to deploy it {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already, including an AzureML step operator? Check out the [in-browser stack deployment wizard](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md), the [stack registration wizard](../../how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md), or [the ZenML Azure Terraform module](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register this stack component. {% endhint %} * Create a `Machine learning` [workspace on Azure](https://docs.microsoft.com/en-us/azure/machine-learning/quickstart-create-resources). This should include an Azure container registry and an Azure storage account that will be used as part of your stack. * (Optional) Once your resource is created, you can head over to the `Azure Machine Learning Studio` and [create a compute instance or cluster](https://learn.microsoft.com/en-us/azure/machine-learning/how-to-create-compute-instance?view=azureml-api-2&tabs=python) to run your pipelines. If omitted, the AzureML step operator will use the serverless compute target or will provision a new compute target on the fly, depending on the settings used to configure the step operator. * (Optional) Create a [Service Principal](https://docs.microsoft.com/en-us/azure/developer/java/sdk/identity-service-principal-auth) for authentication. This is required if you intend to use a service connector to authenticate your step operator. ### How to use it To use the AzureML step operator, we need: * The ZenML `azure` integration installed. If you haven't done so, run ```shell zenml integration install azure ``` * [Docker](https://www.docker.com) installed and running. * An [Azure container registry](../container-registries/azure.md) as part of your stack. Take a look [here](../container-registries/azure.md#how-to-deploy-it) for a guide on how to set that up. * An [Azure artifact store](../artifact-stores/azure.md) as part of your stack. This is needed so that both your orchestration environment and AzureML can read and write step artifacts. Take a look [here](../container-registries/azure.md#how-to-deploy-it) for a guide on how to set that up. * An AzureML workspace and an optional compute cluster. Note that the AzureML workspace can share the Azure container registry and Azure storage account that are required above. See the [deployment section](azureml.md#how-to-deploy-it) for detailed instructions. There are two ways you can authenticate your step operator to be able to run steps on Azure: {% tabs %} {% tab title="Authentication via Service Connector" %} The recommended way to authenticate your AzureML step operator is by registering or using an existing [Azure Service Connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md) and connecting it to your AzureML step operator. The credentials configured for the connector must have permissions to create and manage AzureML jobs (e.g. [the `AzureML Data Scientist` and `AzureML Compute Operator` managed roles](https://learn.microsoft.com/en-us/azure/machine-learning/how-to-assign-roles?view=azureml-api-2&tabs=team-lead)). The AzureML step operator uses the `azure-generic` resource type, so make sure to configure the connector accordingly: ```shell zenml service-connector register --type azure -i zenml step-operator register \ --flavor=azureml \ --subscription_id= \ --resource_group= \ --workspace_name= \ # --compute_target_name= # optionally specify an existing compute target zenml step-operator connect --connector zenml stack register -s ... --set ``` {% endtab %} {% tab title="Implicit Authentication" %} If you don't connect your step operator to a service connector: * If using a [local orchestrator](../orchestrators/local.md): ZenML will try to implicitly authenticate to Azure via the local [Azure CLI configuration](https://learn.microsoft.com/en-us/cli/azure/authenticate-azure-cli-interactively). Make sure the Azure CLI has permissions to create and manage AzureML jobs (e.g. [the `AzureML Data Scientist` and `AzureML Compute Operator` managed roles](https://learn.microsoft.com/en-us/azure/machine-learning/how-to-assign-roles?view=azureml-api-2&tabs=team-lead)). * If using a remote orchestrator: the remote environment in which the orchestrator runs needs to be able to implicitly authenticate to Azure and have permissions to create and manage AzureML jobs. This is only possible if the orchestrator is also running in Azure and uses a form of implicit workload authentication like a service role. If this is not the case, you will need to use a service connector. ```shell zenml step-operator register \ --flavor=azureml \ --subscription_id= \ --resource_group= \ --workspace_name= \ # --compute_target_name= # optionally specify an existing compute target zenml stack register -s ... --set ``` {% endtab %} {% endtabs %} Once you added the step operator to your active stack, you can use it to execute individual steps of your pipeline by specifying it in the `@step` decorator as follows: ```python from zenml import step @step(step_operator=) def trainer(...) -> ...: """Train a model.""" # This step will be executed in AzureML. ``` {% hint style="info" %} ZenML will build a Docker image called `/zenml:` which includes your code and use it to run your steps in AzureML. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. {% endhint %} #### Additional configuration The ZenML AzureML step operator comes with a dedicated class called `AzureMLStepOperatorSettings` for configuring its settings and it controls the compute resources used for step execution in AzureML. Currently, it supports three different modes of operation. 1. Serverless Compute (Default) - Set `mode` to `serverless`. - Other parameters are ignored. 2. Compute Instance - Set `mode` to `compute-instance`. - Requires a `compute_name`. - If a compute instance with the same name exists, it uses the existing compute instance and ignores other parameters. - If a compute instance with the same name doesn't exist, it creates a new compute instance with the `compute_name`. For this process, you can specify `compute_size` and `idle_type_before_shutdown_minutes`. 3. Compute Cluster - Set `mode` to `compute-cluster`. - Requires a `compute_name`. - If a compute cluster with the same name exists, it uses existing cluster, ignores other parameters. - If a compute cluster with the same name doesn't exist, it creates a new compute cluster. Additional parameters can be used for configuring this process. Here is an example how you can use the `AzureMLStepOperatorSettings` to define a compute instance: ```python from zenml.integrations.azure.flavors import AzureMLStepOperatorSettings azureml_settings = AzureMLStepOperatorSettings( mode="compute-instance", compute_name="MyComputeInstance", compute_size="Standard_NC6s_v3", ) @step( settings={ "step_operator": azureml_settings } ) def my_azureml_step(): # YOUR STEP CODE ... ``` You can check out the [AzureMLStepOperatorSettings SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-azure/#zenml.integrations.azure.flavors.azureml\_step\_operator\_flavor.AzureMLStepOperatorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings. #### Enabling CUDA for GPU-backed hardware Note that if you wish to use this step operator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/step-operators/custom.md ================ --- description: Learning how to develop a custom step operator. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Develop a Custom Step Operator {% hint style="info" %} Before diving into the specifics of this component type, it is beneficial to familiarize yourself with our [general guide to writing custom component flavors in ZenML](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). This guide provides an essential understanding of ZenML's component flavor concepts. {% endhint %} ### Base Abstraction The `BaseStepOperator` is the abstract base class that needs to be subclassed in order to run specific steps of your pipeline in a separate environment. As step operators can come in many shapes and forms, the base class exposes a deliberately basic and generic interface: ```python from abc import ABC, abstractmethod from typing import List, Type from zenml.enums import StackComponentType from zenml.stack import StackComponent, StackComponentConfig, Flavor from zenml.config.step_run_info import StepRunInfo class BaseStepOperatorConfig(StackComponentConfig): """Base config for step operators.""" class BaseStepOperator(StackComponent, ABC): """Base class for all ZenML step operators.""" @abstractmethod def launch( self, info: StepRunInfo, entrypoint_command: List[str], ) -> None: """Abstract method to execute a step. Subclasses must implement this method and launch a **synchronous** job that executes the `entrypoint_command`. Args: info: Information about the step run. entrypoint_command: Command that executes the step. """ class BaseStepOperatorFlavor(Flavor): """Base class for all ZenML step operator flavors.""" @property @abstractmethod def name(self) -> str: """Returns the name of the flavor.""" @property def type(self) -> StackComponentType: """Returns the flavor type.""" return StackComponentType.STEP_OPERATOR @property def config_class(self) -> Type[BaseStepOperatorConfig]: """Returns the config class for this flavor.""" return BaseStepOperatorConfig @property @abstractmethod def implementation_class(self) -> Type[BaseStepOperator]: """Returns the implementation class for this flavor.""" ``` {% hint style="info" %} This is a slimmed-down version of the base implementation which aims to highlight the abstraction layer. In order to see the full implementation and get the complete docstrings, please check the [SDK docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-step\_operators/#zenml.step\_operators.base\_step\_operator.BaseStepOperator) . {% endhint %} ### Build your own custom step operator If you want to create your own custom flavor for a step operator, you can follow the following steps: 1. Create a class that inherits from the `BaseStepOperator` class and implement the abstract `launch` method. This method has two main responsibilities: * Preparing a suitable execution environment (e.g. a Docker image): The general environment is highly dependent on the concrete step operator implementation, but for ZenML to be able to run the step it requires you to install some `pip` dependencies. The list of requirements needed to successfully execute the step can be found via the Docker settings `info.pipeline.docker_settings` passed to the `launch()` method. Additionally, you'll have to make sure that all the source code of your ZenML step and pipeline are available within this execution environment. * Running the entrypoint command: Actually running a single step of a pipeline requires knowledge of many ZenML internals and is implemented in the `zenml.step_operators.step_operator_entrypoint_configuration` module. As long as your environment was set up correctly (see the previous bullet point), you can run the step using the command provided via the `entrypoint_command` argument of the `launch()` method. 2. If your step operator allows the specification of per-step resources, make sure to handle the resources defined on the step (`info.config.resource_settings`) that was passed to the `launch()` method. 3. If you need to provide any configuration, create a class that inherits from the `BaseStepOperatorConfig` class adds your configuration parameters. 4. Bring both the implementation and the configuration together by inheriting from the `BaseStepOperatorFlavor` class. Make sure that you give a `name` to the flavor through its abstract property. Once you are done with the implementation, you can register it through the CLI. Please ensure you **point to the flavor class via dot notation**: ```shell zenml step-operator flavor register ``` For example, if your flavor class `MyStepOperatorFlavor` is defined in `flavors/my_flavor.py`, you'd register it by doing: ```shell zenml step-operator flavor register flavors.my_flavor.MyStepOperatorFlavor ``` {% hint style="warning" %} ZenML resolves the flavor class by taking the path where you initialized zenml (via `zenml init`) as the starting point of resolution. Therefore, please ensure you follow [the best practice](../../how-to/infrastructure-deployment/infrastructure-as-code/best-practices.md) of initializing zenml at the root of your repository. If ZenML does not find an initialized ZenML repository in any parent directory, it will default to the current working directory, but usually, it's better to not have to rely on this mechanism and initialize zenml at the root. {% endhint %} Afterward, you should see the new flavor in the list of available flavors: ```shell zenml step-operator flavor list ``` {% hint style="warning" %} It is important to draw attention to when and how these base abstractions are coming into play in a ZenML workflow. * The **CustomStepOperatorFlavor** class is imported and utilized upon the creation of the custom flavor through the CLI. * The **CustomStepOperatorConfig** class is imported when someone tries to register/update a stack component with this custom flavor. Especially, during the registration process of the stack component, the config will be used to validate the values given by the user. As `Config` objects are inherently `pydantic` objects, you can also add your own custom validators here. * The **CustomStepOperator** only comes into play when the component is ultimately in use. The design behind this interaction lets us separate the configuration of the flavor from its implementation. This way we can register flavors and components even when the major dependencies behind their implementation are not installed in our local setting (assuming the `CustomStepOperatorFlavor` and the `CustomStepOperatorConfig` are implemented in a different module/path than the actual `CustomStepOperator`). {% endhint %} #### Enabling CUDA for GPU-backed hardware Note that if you wish to use your custom step operator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/step-operators/kubernetes.md ================ --- description: Executing individual steps in Kubernetes Pods. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Kubernetes Step Operator ZenML's Kubernetes step operator allows you to submit individual steps to be run on Kubernetes pods. ### When to use it You should use the Kubernetes step operator if: * one or more steps of your pipeline require computing resources (CPU, GPU, memory) that are not provided by your orchestrator. * you have access to a Kubernetes cluster. ### How to deploy it The Kubernetes step operator requires a Kubernetes cluster in order to run. There are many ways to deploy a Kubernetes cluster using different cloud providers or on your custom infrastructure, and we can't possibly cover all of them, but you can check out our cloud guide. ### How to use it To use the Kubernetes step operator, we need: * The ZenML `kubernetes` integration installed. If you haven't done so, run ```shell zenml integration install kubernetes ``` * A Kubernetes cluster [deployed](kubernetes.md#how-to-deploy-it) * Either [Docker](https://www.docker.com) installed and running or a remote [image builder](../image-builders/image-builders.md) in your stack. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. This is needed so that both your orchestration environment and Kubernetes Pods can read and write step artifacts. Check out the documentation page of the artifact store you want to use for more information on how to set that up and configure authentication for it. {% hint style="info" %} It is recommended that you set up [a Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) and use it to connect the Kubernetes step operator to the Kubernetes cluster, especially if you are using a Kubernetes cluster managed by a cloud provider like AWS, GCP or Azure. {% endhint %} We can then register the step operator and use it in our stacks. This can be done in two ways: 1. Using a Service Connector configured to access the remote Kubernetes cluster. Depending on your cloud provider, this should be either an [AWS](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md), [Azure](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md) or [GCP](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) service connector. If you're using a Kubernetes cluster that is not provided by any of these, you can use the generic [Kubernetes](../../how-to/infrastructure-deployment/auth-management/kubernetes-service-connector.md) service connector. You can then [connect the stack component to the Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md#connect-stack-components-to-resources): ``` $ zenml step-operator register --flavor kubernetes Running with active stack: 'default' (repository) Successfully registered step operator ``. $ zenml service-connector list-resources --resource-type kubernetes-cluster -e The following 'kubernetes-cluster' resources can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ e33c9fac-5daa-48b2-87bb-0187d3782cde β”‚ aws-iam-multi-eu β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ kubeflowmultitenant ┃ ┃ β”‚ β”‚ β”‚ β”‚ zenbox ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ ed528d5a-d6cb-4fc4-bc52-c3d2d01643e5 β”‚ aws-iam-multi-us β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ zenhacks-cluster ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ 1c54b32a-4889-4417-abbd-42d3ace3d03a β”‚ gcp-sa-multi β”‚ πŸ”΅ gcp β”‚ πŸŒ€ kubernetes-cluster β”‚ zenml-test-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┛ $ zenml step-operator connect --connector aws-iam-multi-us Running with active stack: 'default' (repository) Successfully connected step_operator `` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID β”‚ CONNECTOR NAME β”‚ CONNECTOR TYPE β”‚ RESOURCE TYPE β”‚ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼──────────────────┼────────────────┼───────────────────────┼──────────────────┨ ┃ ed528d5a-d6cb-4fc4-bc52-c3d2d01643e5 β”‚ aws-iam-multi-us β”‚ πŸ”Ά aws β”‚ πŸŒ€ kubernetes-cluster β”‚ zenhacks-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┛ ``` 2. Using the local Kubernetes `kubectl` client. This client needs to be configured with a configuration context pointing to the remote cluster. The `kubernetes_context` configuration attribute must also be configured with the value of that context: ```shell zenml step-operator register \ --flavor=kubernetes \ --kubernetes_context= ``` We can then use the registered step operator in our active stack: ```shell # Add the step operator to the active stack zenml stack update -s ``` Once you added the step operator to your active stack, you can use it to execute individual steps of your pipeline by specifying it in the `@step` decorator as follows: ```python from zenml import step @step(step_operator=) def trainer(...) -> ...: """Train a model.""" # This step will be executed in Kubernetes. ``` {% hint style="info" %} ZenML will build a Docker images which includes your code and use it to run your steps in Kubernetes. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. {% endhint %} #### Interacting with pods via kubectl For debugging, it can sometimes be handy to interact with the Kubernetes pods directly via kubectl. To make this easier, we have added the following labels to all pods: * `run`: the name of the ZenML run. * `pipeline`: the name of the ZenML pipeline associated with this run. E.g., you can use these labels to manually delete all pods related to a specific pipeline: ```shell kubectl delete pod -n zenml -l pipeline=kubernetes_example_pipeline ``` #### Additional configuration For additional configuration of the Kubernetes step operator, you can pass `KubernetesStepOperatorSettings` which allows you to configure (among others) the following attributes: * `pod_settings`: Node selectors, labels, affinity, and tolerations, and image pull secrets to apply to the Kubernetes Pods. These can be either specified using the Kubernetes model objects or as dictionaries. * `service_account_name`: The name of the service account to use for the Kubernetes Pods. ```python from zenml.integrations.kubernetes.flavors import KubernetesStepOperatorSettings from kubernetes.client.models import V1Toleration kubernetes_settings = KubernetesStepOperatorSettings( pod_settings={ "node_selectors": { "cloud.google.com/gke-nodepool": "ml-pool", "kubernetes.io/arch": "amd64" }, "affinity": { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [ { "matchExpressions": [ { "key": "gpu-type", "operator": "In", "values": ["nvidia-tesla-v100", "nvidia-tesla-p100"] } ] } ] } } }, "tolerations": [ V1Toleration( key="gpu", operator="Equal", value="present", effect="NoSchedule" ), V1Toleration( key="high-priority", operator="Exists", effect="PreferNoSchedule" ) ], "resources": { "requests": { "cpu": "2", "memory": "4Gi", "nvidia.com/gpu": "1" }, "limits": { "cpu": "4", "memory": "8Gi", "nvidia.com/gpu": "1" } }, "annotations": { "prometheus.io/scrape": "true", "prometheus.io/port": "8080" }, "volumes": [ { "name": "data-volume", "persistentVolumeClaim": { "claimName": "ml-data-pvc" } }, { "name": "config-volume", "configMap": { "name": "ml-config" } } ], "volume_mounts": [ { "name": "data-volume", "mountPath": "/mnt/data" }, { "name": "config-volume", "mountPath": "/etc/ml-config", "readOnly": True } ], "host_ipc": True, "image_pull_secrets": ["regcred", "gcr-secret"], "labels": { "app": "ml-pipeline", "environment": "production", "team": "data-science" } }, kubernetes_namespace="ml-pipelines", service_account_name="zenml-pipeline-runner" ) @step( settings={ "step_operator": kubernetes_settings } ) def my_kubernetes_step(): ... ``` Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-kubernetes/#zenml.integrations.kubernetes.flavors.kubernetes\_step\_operator\_flavor.KubernetesStepOperatorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings. For more information and a full list of configurable attributes of the Kubernetes steop operator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-kubernetes/#zenml.integrations.kubernetes.step\_operators.kubernetes\step\_operator.KubernetesStepOperator) . #### Enabling CUDA for GPU-backed hardware Note that if you wish to use this step operator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/step-operators/modal.md ================ --- description: Executing individual steps in Modal. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Modal Step Operator [Modal](https://modal.com) is a platform for running cloud infrastructure. It offers specialized compute instances to run your code and has a fast execution time, especially around building Docker images and provisioning hardware. ZenML's Modal step operator allows you to submit individual steps to be run on Modal compute instances. ### When to use it You should use the Modal step operator if: * You need fast execution time for steps that require computing resources (CPU, GPU, memory). * You want to easily specify the exact hardware requirements (e.g., GPU type, CPU count, memory) for each step. * You have access to Modal. ### How to deploy it To use the Modal step operator: * [Sign up for a Modal account](https://modal.com/signup) if you haven't already. * Install the Modal CLI by running `pip install modal` (or `zenml integration install modal`) and authenticate by running `modal setup` in your terminal. ### How to use it To use the Modal step operator, we need: * The ZenML `modal` integration installed. If you haven't done so, run ```shell zenml integration install modal ``` * Docker installed and running. * A cloud artifact store as part of your stack. This is needed so that both your orchestration environment and Modal can read and write step artifacts. Any cloud artifact store supported by ZenML will work with Modal. * A cloud container registry as part of your stack. Any cloud container registry supported by ZenML will work with Modal. We can then register the step operator: ```shell zenml step-operator register --flavor=modal zenml stack update -s ... ``` Once you added the step operator to your active stack, you can use it to execute individual steps of your pipeline by specifying it in the `@step` decorator as follows: ```python from zenml import step @step(step_operator=) def trainer(...) -> ...: """Train a model.""" # This step will be executed in Modal. ``` {% hint style="info" %} ZenML will build a Docker image which includes your code and use it to run your steps in Modal. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. {% endhint %} #### Additional configuration You can specify the hardware requirements for each step using the `ResourceSettings` class as described in our documentation on [resource settings](../../how-to/pipeline-development/training-with-gpus/README.md): ```python from zenml.config import ResourceSettings from zenml.integrations.modal.flavors import ModalStepOperatorSettings modal_settings = ModalStepOperatorSettings(gpu="A100") resource_settings = ResourceSettings( cpu=2, memory="32GB" ) @step( step_operator="modal", # or whatever name you used when registering the step operator settings={ "step_operator": modal_settings, "resources": resource_settings } ) def my_modal_step(): ... ``` {% hint style="info" %} Note that the `cpu` parameter in `ResourceSettings` currently only accepts a single integer value. This specifies a soft minimum limit - Modal will guarantee at least this many physical cores, but the actual usage could be higher. The CPU cores/hour will also determine the minimum price paid for the compute resources. For example, with the configuration above (2 CPUs and 32GB memory), the minimum cost would be approximately $1.03 per hour ((0.135 * 2) + (0.024 * 32) = $1.03). {% endhint %} This will run `my_modal_step` on a Modal instance with 1 A100 GPU, 2 CPUs, and 32GB of CPU memory. Check out the [Modal docs](https://modal.com/docs/reference/modal.gpu) for the full list of supported GPU types and the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-modal/#zenml.integrations.modal.flavors.modal\_step\_operator\_flavor.ModalStepOperatorSettings) for more details on the available settings. The settings do allow you to specify the region and cloud provider, but these settings are only available for Modal Enterprise and Team plan customers. Moreover, certain combinations of settings are not available. It is suggested to err on the side of looser settings rather than more restrictive ones to avoid pipeline execution failures. In the case of failures, however, Modal provides detailed error messages that can help identify what is incompatible. See more in the [Modal docs on region selection](https://modal.com/docs/guide/region-selection) for more details.
ZenML Scarf
================ File: docs/book/component-guide/step-operators/sagemaker.md ================ --- description: Executing individual steps in SageMaker. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Amazon SageMaker [SageMaker](https://aws.amazon.com/sagemaker/) offers specialized compute instances to run your training jobs and has a comprehensive UI to track and manage your models and logs. ZenML's SageMaker step operator allows you to submit individual steps to be run on Sagemaker compute instances. ### When to use it You should use the SageMaker step operator if: * one or more steps of your pipeline require computing resources (CPU, GPU, memory) that are not provided by your orchestrator. * you have access to SageMaker. If you're using a different cloud provider, take a look at the [Vertex](vertex.md) or [AzureML](azureml.md) step operators. ### How to deploy it Create a role in the IAM console that you want the jobs running in SageMaker to assume. This role should at least have the `AmazonS3FullAccess` and `AmazonSageMakerFullAccess` policies applied. Check [here](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-roles.html#sagemaker-roles-create-execution-role) for a guide on how to set up this role. ### How to use it To use the SageMaker step operator, we need: * The ZenML `aws` integration installed. If you haven't done so, run ```shell zenml integration install aws ``` * [Docker](https://www.docker.com) installed and running. * An IAM role with the correct permissions. See the [deployment section](sagemaker.md#how-to-deploy-it) for detailed instructions. * An [AWS container registry](../container-registries/aws.md) as part of our stack. Take a look [here](../container-registries/aws.md#how-to-deploy-it) for a guide on how to set that up. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. This is needed so that both your orchestration environment and SageMaker can read and write step artifacts. Check out the documentation page of the artifact store you want to use for more information on how to set that up and configure authentication for it. * An instance type that we want to execute our steps on. See [here](https://docs.aws.amazon.com/sagemaker/latest/dg/notebooks-available-instance-types.html) for a list of available instance types. * (Optional) An experiment that is used to group SageMaker runs. Check [this guide](https://docs.aws.amazon.com/sagemaker/latest/dg/experiments-create.html) to see how to create an experiment. There are two ways you can authenticate your orchestrator to AWS to be able to run steps on SageMaker: {% tabs %} {% tab title="Authentication via Service Connector" %} The recommended way to authenticate your SageMaker step operator is by registering or using an existing [AWS Service Connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md) and connecting it to your SageMaker step operator. The credentials configured for the connector must have permissions to create and manage SageMaker runs (e.g. [the `AmazonSageMakerFullAccess` managed policy](https://docs.aws.amazon.com/sagemaker/latest/dg/security-iam-awsmanpol.html) permissions). The SageMaker step operator uses these `aws-generic` resource type, so make sure to configure the connector accordingly: ```shell zenml service-connector register --type aws -i zenml step-operator register \ --flavor=sagemaker \ --role= \ --instance_type= \ # --experiment_name= # optionally specify an experiment to assign this run to zenml step-operator connect --connector zenml stack register -s ... --set ``` {% endtab %} {% tab title="Implicit Authentication" %} If you don't connect your step operator to a service connector: * If using a [local orchestrator](../orchestrators/local.md): ZenML will try to implicitly authenticate to AWS via the `default` profile in your local [AWS configuration file](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html). Make sure this profile has permissions to create and manage SageMaker runs (e.g. [the `AmazonSageMakerFullAccess` managed policy](https://docs.aws.amazon.com/sagemaker/latest/dg/security-iam-awsmanpol.html) permissions). * If using a remote orchestrator: the remote environment in which the orchestrator runs needs to be able to implicitly authenticate to AWS and assume the IAM role specified when registering the SageMaker step operator. This is only possible if the orchestrator is also running in AWS and uses a form of implicit workload authentication like the IAM role of an EC2 instance. If this is not the case, you will need to use a service connector. ```shell zenml step-operator register \ --flavor=sagemaker \ --role= \ --instance_type= \ # --experiment_name= # optionally specify an experiment to assign this run to zenml stack register -s ... --set python run.py # Authenticates with `default` profile in `~/.aws/config` ``` {% endtab %} {% endtabs %} Once you added the step operator to your active stack, you can use it to execute individual steps of your pipeline by specifying it in the `@step` decorator as follows: ```python from zenml import step @step(step_operator= ) def trainer(...) -> ...: """Train a model.""" # This step will be executed in SageMaker. ``` {% hint style="info" %} ZenML will build a Docker image called `/zenml:` which includes your code and use it to run your steps in SageMaker. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. {% endhint %} #### Additional configuration For additional configuration of the SageMaker step operator, you can pass `SagemakerStepOperatorSettings` when defining or running your pipeline. Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-aws/#zenml.integrations.aws.flavors.sagemaker\_step\_operator\_flavor.SagemakerStepOperatorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings. For more information and a full list of configurable attributes of the SageMaker step operator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-aws/#zenml.integrations.aws.step\_operators.sagemaker\_step\_operator.SagemakerStepOperator) . #### Enabling CUDA for GPU-backed hardware Note that if you wish to use this step operator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/step-operators/spark-kubernetes.md ================ --- description: Executing individual steps on Spark --- # Spark The `spark` integration brings two different step operators: * **Step Operator**: The `SparkStepOperator` serves as the base class for all the Spark-related step operators. * **Step Operator**: The `KubernetesSparkStepOperator` is responsible for launching ZenML steps as Spark applications with Kubernetes as a cluster manager. ## Step Operators: `SparkStepOperator` A summarized version of the implementation can be summarized in two parts. First, the configuration: ```python from typing import Optional, Dict, Any from zenml.step_operators import BaseStepOperatorConfig class SparkStepOperatorConfig(BaseStepOperatorConfig): """Spark step operator config. Attributes: master: is the master URL for the cluster. You might see different schemes for different cluster managers which are supported by Spark like Mesos, YARN, or Kubernetes. Within the context of this PR, the implementation supports Kubernetes as a cluster manager. deploy_mode: can either be 'cluster' (default) or 'client' and it decides where the driver node of the application will run. submit_kwargs: is the JSON string of a dict, which will be used to define additional params if required (Spark has quite a lot of different parameters, so including them, all in the step operator was not implemented). """ master: str deploy_mode: str = "cluster" submit_kwargs: Optional[Dict[str, Any]] = None ``` and then the implementation: ```python from typing import List from pyspark.conf import SparkConf from zenml.step_operators import BaseStepOperator class SparkStepOperator(BaseStepOperator): """Base class for all Spark-related step operators.""" def _resource_configuration( self, spark_config: SparkConf, resource_configuration: "ResourceSettings", ) -> None: """Configures Spark to handle the resource configuration.""" def _backend_configuration( self, spark_config: SparkConf, step_config: "StepConfiguration", ) -> None: """Configures Spark to handle backends like YARN, Mesos or Kubernetes.""" def _io_configuration( self, spark_config: SparkConf ) -> None: """Configures Spark to handle different input/output sources.""" def _additional_configuration( self, spark_config: SparkConf ) -> None: """Appends the user-defined configuration parameters.""" def _launch_spark_job( self, spark_config: SparkConf, entrypoint_command: List[str] ) -> None: """Generates and executes a spark-submit command.""" def launch( self, info: "StepRunInfo", entrypoint_command: List[str], ) -> None: """Launches the step on Spark.""" ``` Under the base configuration, you will see the main configuration parameters: * `master` is the master URL for the cluster where Spark will run. You might see different schemes for this URL with varying cluster managers such as Mesos, YARN, or Kubernetes. * `deploy_mode` can either be 'cluster' (default) or 'client' and it decides where the driver node of the application will run. * `submit_args` is the JSON string of a dictionary, which will be used to define additional parameters if required ( Spark has a wide variety of parameters, thus including them all in a single class was deemed unnecessary.). In addition to this configuration, the `launch` method of the step operator gets additional configuration parameters from the `DockerSettings` and `ResourceSettings`. As a result, the overall configuration happens in 4 base methods: * `_resource_configuration` translates the ZenML `ResourceSettings` object to Spark's own resource configuration. * `_backend_configuration` is responsible for cluster-manager-specific configuration. * `_io_configuration` is a critical method. Even though we have materializers, Spark might require additional packages and configuration to work with a specific filesystem. This method is used as an interface to provide this configuration. * `_additional_configuration` takes the `submit_args`, converts, and appends them to the overall configuration. Once the configuration is completed, `_launch_spark_job` comes into play. This takes the completed configuration and runs a Spark job on the given `master` URL with the specified `deploy_mode`. By default, this is achieved by creating and executing a `spark-submit` command. ### Warning In its first iteration, the pre-configuration with `_io_configuration` method is only effective when it is paired with an `S3ArtifactStore` (which has an authentication secret). When used with other artifact store flavors, you might be required to provide additional configuration through the `submit_args`. ## Stack Component: `KubernetesSparkStepOperator` The `KubernetesSparkStepOperator` is implemented by subclassing the base `SparkStepOperator` and uses the `PipelineDockerImageBuilder` class to build and push the required Docker images. ```python from typing import Optional from zenml.integrations.spark.step_operators.spark_step_operator import ( SparkStepOperatorConfig ) class KubernetesSparkStepOperatorConfig(SparkStepOperatorConfig): """Config for the Kubernetes Spark step operator.""" namespace: Optional[str] = None service_account: Optional[str] = None ``` ```python from pyspark.conf import SparkConf from zenml.utils.pipeline_docker_image_builder import PipelineDockerImageBuilder from zenml.integrations.spark.step_operators.spark_step_operator import ( SparkStepOperator ) class KubernetesSparkStepOperator(SparkStepOperator): """Step operator which runs Steps with Spark on Kubernetes.""" def _backend_configuration( self, spark_config: SparkConf, step_config: "StepConfiguration", ) -> None: """Configures Spark to run on Kubernetes.""" # Build and push the image docker_image_builder = PipelineDockerImageBuilder() image_name = docker_image_builder.build_and_push_docker_image(...) # Adjust the spark configuration spark_config.set("spark.kubernetes.container.image", image_name) ... ``` For Kubernetes, there are also some additional important configuration parameters: * `namespace` is the namespace under which the driver and executor pods will run. * `service_account` is the service account that will be used by various Spark components (to create and watch the pods). Additionally, the `_backend_configuration` method is adjusted to handle the Kubernetes-specific configuration. ## When to use it You should use the Spark step operator: * when you are dealing with large amounts of data. * when you are designing a step that can benefit from distributed computing paradigms in terms of time and resources. ## How to deploy it To use the `KubernetesSparkStepOperator` you will need to setup a few things first: * **Remote ZenML server:** See the [deployment guide](../../getting-started/deploying-zenml/README.md) for more information. * **Kubernetes cluster:** There are many ways to deploy a Kubernetes cluster using different cloud providers or on your custom infrastructure. For AWS, you can follow the [Spark EKS Setup Guide](spark-kubernetes.md#spark-eks-setup-guide) below. ### Spark EKS Setup Guide The following guide will walk you through how to spin up and configure a [Amazon Elastic Kubernetes Service](https://aws.amazon.com/eks/) with Spark on it: #### EKS Kubernetes Cluster * Follow [this guide](https://docs.aws.amazon.com/eks/latest/userguide/service\_IAM\_role.html#create-service-role) to create an Amazon EKS cluster role. * Follow [this guide](https://docs.aws.amazon.com/eks/latest/userguide/create-node-role.html#create-worker-node-role) to create an Amazon EC2 node role. * Go to the [IAM website](https://console.aws.amazon.com/iam), and select `Roles` to edit both roles. * Attach the `AmazonRDSFullAccess` and `AmazonS3FullAccess` policies to both roles. * Go to the [EKS website](https://console.aws.amazon.com/eks). * Make sure the correct region is selected on the top right. * Click on `Add cluster` and select `Create`. * Enter a name and select the **cluster role** for `Cluster service role`. * Keep the default values for the networking and logging steps and create the cluster. * Note down the cluster name and the API server endpoint: ```bash EKS_CLUSTER_NAME= EKS_API_SERVER_ENDPOINT= ``` * After the cluster is created, select it and click on `Add node group` in the `Compute` tab. * Enter a name and select the **node role**. * For the instance type, we recommend `t3a.xlarge`, as it provides up to 4 vCPUs and 16 GB of memory. #### Docker image for the Spark drivers and executors When you want to run your steps on a Kubernetes cluster, Spark will require you to choose a base image for the driver and executor pods. Normally, for this purpose, you can either use one of the base images in [Spark’s dockerhub](https://hub.docker.com/r/apache/spark-py/tags) or create an image using the [docker-image-tool](https://spark.apache.org/docs/latest/running-on-kubernetes.html#docker-images) which will use your own Spark installation and build an image. When using Spark in EKS, you need to use the latter and utilize the `docker-image-tool`. However, before the build process, you also need to download the following packages * [`hadoop-aws` = 3.3.1](https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-aws/3.3.1) * [`aws-java-sdk-bundle` = 1.12.150](https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-bundle/1.12.150) and put them in the `jars` folder within your Spark installation. Once that is set up, you can build the image as follows: ```bash cd $SPARK_HOME # If this empty for you then you need to set the SPARK_HOME variable which points to your Spark installation SPARK_IMAGE_TAG= ./bin/docker-image-tool.sh -t $SPARK_IMAGE_TAG -p kubernetes/dockerfiles/spark/bindings/python/Dockerfile -u 0 build BASE_IMAGE_NAME=spark-py:$SPARK_IMAGE_TAG ``` If you are working on an M1 Mac, you will need to build the image for the amd64 architecture, by using the prefix `-X` on the previous command. For example: ```bash ./bin/docker-image-tool.sh -X -t $SPARK_IMAGE_TAG -p kubernetes/dockerfiles/spark/bindings/python/Dockerfile -u 0 build ``` #### Configuring RBAC Additionally, you may need to create the several resources in Kubernetes in order to give Spark access to edit/manage your driver executor pods. To do so, create a file called `rbac.yaml` with the following content: ```yaml apiVersion: v1 kind: Namespace metadata: name: spark-namespace --- apiVersion: v1 kind: ServiceAccount metadata: name: spark-service-account namespace: spark-namespace --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: spark-role namespace: spark-namespace subjects: - kind: ServiceAccount name: spark-service-account namespace: spark-namespace roleRef: kind: ClusterRole name: edit apiGroup: rbac.authorization.k8s.io --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} ``` And then execute the following command to create the resources: ```bash aws eks --region=$REGION update-kubeconfig --name=$EKS_CLUSTER_NAME kubectl create -f rbac.yaml ``` Lastly, note down the **namespace** and the name of the **service account** since you will need them when registering the stack component in the next step. ## How to use it To use the `KubernetesSparkStepOperator`, you need: * the ZenML `spark` integration. If you haven't installed it already, run ```shell zenml integration install spark ``` * [Docker](https://www.docker.com) installed and running. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. * A [remote container registry](../container-registries/container-registries.md) as part of your stack. * A Kubernetes cluster [deployed](spark-kubernetes.md#how-to-deploy-it). We can then register the step operator and use it in our active stack: ```bash zenml step-operator register spark_step_operator \ --flavor=spark-kubernetes \ --master=k8s://$EKS_API_SERVER_ENDPOINT \ --namespace= \ --service_account= ``` ```bash # Register the stack zenml stack register spark_stack \ -o default \ -s spark_step_operator \ -a spark_artifact_store \ -c spark_container_registry \ -i local_builder \ --set ``` Once you added the step operator to your active stack, you can use it to execute individual steps of your pipeline by specifying it in the `@step` decorator as follows: ```python from zenml import step @step(step_operator=) def step_on_spark(...) -> ...: """Some step that should run with Spark on Kubernetes.""" ... ``` After successfully running any step with a `KubernetesSparkStepOperator`, you should be able to see that a Spark driver pod was created in your cluster for each pipeline step when running `kubectl get pods -n $KUBERNETES_NAMESPACE`. {% hint style="info" %} Instead of hardcoding a step operator name, you can also use the [Client](../../reference/python-client.md) to dynamically use the step operator of your active stack: ```python from zenml.client import Client step_operator = Client().active_stack.step_operator @step(step_operator=step_operator.name) def step_on_spark(...) -> ...: ... ``` {% endhint %} ### Additional configuration For additional configuration of the Spark step operator, you can pass `SparkStepOperatorSettings` when defining or running your pipeline. Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-spark/#zenml.integrations.spark.flavors.spark\_step\_operator\_flavor.SparkStepOperatorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings.
ZenML Scarf
================ File: docs/book/component-guide/step-operators/step-operators.md ================ --- icon: arrow-progress description: Executing individual steps in specialized environments. --- # Step Operators The step operator enables the execution of individual pipeline steps in specialized runtime environments that are optimized for certain workloads. These specialized environments can give your steps access to resources like GPUs or distributed processing frameworks like [Spark](https://spark.apache.org/). {% hint style="info" %} **Comparison to orchestrators:** The [orchestrator](../orchestrators/orchestrators.md) is a mandatory stack component that is responsible for executing all steps of a pipeline in the correct order and providing additional features such as scheduling pipeline runs. The step operator on the other hand is used to only execute individual steps of the pipeline in a separate environment in case the environment provided by the orchestrator is not feasible. {% endhint %} ### When to use it A step operator should be used if one or more steps of a pipeline require resources that are not available in the runtime environments provided by the [orchestrator](../orchestrators/orchestrators.md). An example would be a step that trains a computer vision model and requires a GPU to run in a reasonable time, combined with a [Kubeflow orchestrator](../orchestrators/kubeflow.md) running on a Kubernetes cluster that does not contain any GPU nodes. In that case, it makes sense to include a step operator like [SageMaker](sagemaker.md), [Vertex](vertex.md), or [AzureML](azureml.md) to execute the training step with a GPU. ### Step Operator Flavors Step operators to execute steps on one of the big cloud providers are provided by the following ZenML integrations: | Step Operator | Flavor | Integration | Notes | |------------------------------------|-------------|-------------|--------------------------------------------------------------------------| | [AzureML](azureml.md) | `azureml` | `azure` | Uses AzureML to execute steps | | [Kubernetes](kubernetes.md) | `kubernetes` | `kubernetes` | Uses Kubernetes Pods to execute steps | | [Modal](modal.md) | `modal` | `modal` | Uses Modal to execute steps | | [SageMaker](sagemaker.md) | `sagemaker` | `aws` | Uses SageMaker to execute steps | | [Spark](spark-kubernetes.md) | `spark` | `spark` | Uses Spark on Kubernetes to execute steps in a distributed manner | | [Vertex](vertex.md) | `vertex` | `gcp` | Uses Vertex AI to execute steps | | [Custom Implementation](custom.md) | _custom_ | | Extend the step operator abstraction and provide your own implementation | If you would like to see the available flavors of step operators, you can use the command: ```shell zenml step-operator flavor list ``` ### How to use it You don't need to directly interact with any ZenML step operator in your code. As long as the step operator that you want to use is part of your active [ZenML stack](../../user-guide/production-guide/understand-stacks.md), you can simply specify it in the `@step` decorator of your step. ```python from zenml import step @step(step_operator= ) def my_step(...) -> ...: ... ``` #### Specifying per-step resources If your steps require additional hardware resources, you can specify them on your steps as described [here](../../how-to/pipeline-development/training-with-gpus/README.md). #### Enabling CUDA for GPU-backed hardware Note that if you wish to use step operators to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/step-operators/vertex.md ================ --- description: Executing individual steps in Vertex AI. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Google Cloud VertexAI [Vertex AI](https://cloud.google.com/vertex-ai) offers specialized compute instances to run your training jobs and has a comprehensive UI to track and manage your models and logs. ZenML's Vertex AI step operator allows you to submit individual steps to be run on Vertex AI compute instances. ### When to use it You should use the Vertex step operator if: * one or more steps of your pipeline require computing resources (CPU, GPU, memory) that are not provided by your orchestrator. * you have access to Vertex AI. If you're using a different cloud provider, take a look at the [SageMaker](sagemaker.md) or [AzureML](azureml.md) step operators. ### How to deploy it * Enable Vertex AI [here](https://console.cloud.google.com/vertex-ai). * Create a [service account](https://cloud.google.com/iam/docs/service-accounts) with the right permissions to create Vertex AI jobs (`roles/aiplatform.admin`) and push to the container registry (`roles/storage.admin`). ### How to use it To use the Vertex step operator, we need: * The ZenML `gcp` integration installed. If you haven't done so, run ```shell zenml integration install gcp ``` * [Docker](https://www.docker.com) installed and running. * Vertex AI enabled and a service account file. See the [deployment section](vertex.md#how-to-deploy-it) for detailed instructions. * A [GCR container registry](../container-registries/gcp.md) as part of our stack. * (Optional) A machine type that we want to execute our steps on (this defaults to `n1-standard-4`). See [here](https://cloud.google.com/vertex-ai/docs/training/configure-compute#machine-types) for a list of available machine types. * A [remote artifact store](../artifact-stores/artifact-stores.md) as part of your stack. This is needed so that both your orchestration environment and VertexAI can read and write step artifacts. Check out the documentation page of the artifact store you want to use for more information on how to set that up and configure authentication for it. You have three different options to provide GCP credentials to the step operator: * use the [`gcloud` CLI](https://cloud.google.com/sdk/gcloud) to authenticate locally with GCP. This only works in combination with the local orchestrator. ```shell gcloud auth login zenml step-operator register \ --flavor=vertex \ --project= \ --region= \ # --machine_type= # optionally specify the type of machine to run on ``` * configure the orchestrator to use a [service account key file](https://cloud.google.com/iam/docs/creating-managing-service-account-keys) to authenticate with GCP by setting the `service_account_path` parameter in the orchestrator configuration to point to a service account key file. This also works only in combination with the local orchestrator. ```shell zenml step-operator register \ --flavor=vertex \ --project= \ --region= \ --service_account_path= \ # --machine_type= # optionally specify the type of machine to run on ``` * (recommended) configure [a GCP Service Connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) with GCP credentials coming from a [service account key file](https://cloud.google.com/iam/docs/creating-managing-service-account-keys) or the local `gcloud` CLI set up with user account credentials and then link the Vertex AI Step Operator stack component to the Service Connector. This option works with any orchestrator. ```shell zenml service-connector register --type gcp --auth-method=service-account --project_id= --service_account_json=@ --resource-type gcp-generic # Or, as an alternative, you could use the GCP user account locally set up with gcloud # zenml service-connector register --type gcp --resource-type gcp-generic --auto-configure zenml step-operator register \ --flavor=vertex \ --region= \ # --machine_type= # optionally specify the type of machine to run on zenml step-operator connect --connector ``` We can then use the registered step operator in our active stack: ```shell # Add the step operator to the active stack zenml stack update -s ``` Once you added the step operator to your active stack, you can use it to execute individual steps of your pipeline by specifying it in the `@step` decorator as follows: ```python from zenml import step @step(step_operator=) def trainer(...) -> ...: """Train a model.""" # This step will be executed in Vertex. ``` {% hint style="info" %} ZenML will build a Docker image called `/zenml:` which includes your code and use it to run your steps in Vertex AI. Check out [this page](../../how-to/customize-docker-builds/README.md) if you want to learn more about how ZenML builds these images and how you can customize them. {% endhint %} #### Additional configuration You can specify the service account, network and reserved IP ranges to use for the VertexAI `CustomJob` by passing the `service_account`, `network` and `reserved_ip_ranges` parameters to the `step-operator register` command: ```shell zenml step-operator register \ --flavor=vertex \ --project= \ --region= \ --service_account= # optionally specify the service account to use for the VertexAI CustomJob --network= # optionally specify the network to use for the VertexAI CustomJob --reserved_ip_ranges= # optionally specify the reserved IP range to use for the VertexAI CustomJob ``` For additional configuration of the Vertex step operator, you can pass `VertexStepOperatorSettings` when defining or running your pipeline. ```python from zenml import step from zenml.integrations.gcp.flavors.vertex_step_operator_flavor import VertexStepOperatorSettings @step(step_operator=, settings={"step_operator": VertexStepOperatorSettings( accelerator_type= "NVIDIA_TESLA_T4", # see https://cloud.google.com/vertex-ai/docs/reference/rest/v1/MachineSpec#AcceleratorType accelerator_count = 1, machine_type = "n1-standard-2", # see https://cloud.google.com/vertex-ai/docs/training/configure-compute#machine-types disk_type = "pd-ssd", # see https://cloud.google.com/vertex-ai/docs/training/configure-storage#disk-types disk_size_gb = 100, # see https://cloud.google.com/vertex-ai/docs/training/configure-storage#disk-size )}) def trainer(...) -> ...: """Train a model.""" # This step will be executed in Vertex. ``` Check out the [SDK docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-gcp/#zenml.integrations.gcp.flavors.vertex\_step\_operator\_flavor.VertexStepOperatorSettings) for a full list of available attributes and [this docs page](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) for more information on how to specify settings. For more information and a full list of configurable attributes of the Vertex step operator, check out the [SDK Docs](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-gcp/#zenml.integrations.gcp.step\_operators.vertex\_step\_operator.VertexStepOperator) . #### Enabling CUDA for GPU-backed hardware Note that if you wish to use this step operator to run steps on a GPU, you will need to follow [the instructions on this page](../../how-to/pipeline-development/training-with-gpus/README.md) to ensure that it works. It requires adding some extra settings customization and is essential to enable CUDA for the GPU to give its full acceleration.
ZenML Scarf
================ File: docs/book/component-guide/component-guide.md ================ --- description: Overview of categories of MLOps components. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # πŸ“œ Overview If you are new to the world of MLOps, it is often daunting to be immediately faced with a sea of tools that seemingly all promise and do the same things. It is useful in this case to try to categorize tools in various groups in order to understand their value in your toolchain in a more precise manner. ZenML tackles this problem by introducing the concept of [Stacks and Stack Components](../user-guide/production-guide/understand-stacks.md). These stack components represent categories, each of which has a particular function in your MLOps pipeline. ZenML realizes these stack components as base abstractions that standardize the entire workflow for your team. In order to then realize the benefit, one can write a concrete implementation of the [abstraction](../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md), or use one of the many built-in [integrations](README.md) that implement these abstractions for you. Here is a full list of all stack components currently supported in ZenML, with a description of the role of that component in the MLOps process: | **Type of Stack Component** | **Description** | | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | | [Orchestrator](./orchestrators/orchestrators.md) | Orchestrating the runs of your pipeline | | [Artifact Store](./artifact-stores/artifact-stores.md) | Storage for the artifacts created by your pipelines | | [Container Registry](./container-registries/container-registries.md) | Store for your containers | | [Step Operator](./step-operators/step-operators.md) | Execution of individual steps in specialized runtime environments | | [Model Deployer](./model-deployers/model-deployers.md) | Services/platforms responsible for online model serving | | [Feature Store](./feature-stores/feature-stores.md) | Management of your data/features | | [Experiment Tracker](./experiment-trackers/experiment-trackers.md) | Tracking your ML experiments | | [Alerter](./alerters/alerters.md) | Sending alerts through specified channels | | [Annotator](./annotators/annotators.md) | Labeling and annotating data | | [Data Validator](./data-validators/data-validators.md) | Data and model validation | | [Image Builder](./image-builders/image-builders.md) | Builds container images. | | [Model Registry](./model-registries/model-registries.md) | Manage and interact with ML Models | Each pipeline run that you execute with ZenML will require a **stack** and each **stack** will be required to include at least an orchestrator and an artifact store. Apart from these two, the other components are optional and to be added as your pipeline evolves in MLOps maturity. ## Writing custom component flavors You can take control of how ZenML behaves by creating your own components. This is done by writing custom component `flavors`. To learn more, head over to [the general guide on writing component flavors](../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md), or read more specialized guides for specific component types (e.g. the [custom orchestrator guide](orchestrators/custom.md)).
ZenML Scarf
================ File: docs/book/component-guide/integration-overview.md ================ --- description: Overview of third-party ZenML integrations. --- {% hint style="warning" %} This is an older version of the ZenML documentation. To read and view the latest version please [visit this up-to-date URL](https://docs.zenml.io). {% endhint %} # Integration overview Categorizing the MLOps stack is a good way to write abstractions for an MLOps pipeline and standardize your processes. But ZenML goes further and also provides concrete implementations of these categories by **integrating** with various tools for each category. Once code is organized into a ZenML pipeline, you can supercharge your ML workflows with the best-in-class solutions from various MLOps areas. For example, you can orchestrate your ML pipeline workflows using [Airflow](orchestrators/airflow.md) or [Kubeflow](orchestrators/kubeflow.md), track experiments using [MLflow Tracking](experiment-trackers/mlflow.md) or [Weights & Biases](experiment-trackers/wandb.md), and transition seamlessly from a local [MLflow deployment](model-deployers/mlflow.md) to a deployed model on Kubernetes using [Seldon Core](model-deployers/seldon.md). There are lots of moving parts for all the MLOps tooling and infrastructure you require for ML in production and ZenML brings them all together and enables you to manage them in one place. This also allows you to delay the decision of which MLOps tool to use in your stack as you have no vendor lock-in with ZenML and can easily switch out tools as soon as your requirements change. ![ZenML is the glue](../.gitbook/assets/zenml-is-the-glue.jpeg) ## Available integrations We have a [dedicated webpage](https://zenml.io/integrations) that indexes all supported ZenML integrations and their categories. Another easy way of seeing a list of integrations is to see the list of directories in the [integrations directory](https://github.com/zenml-io/zenml/tree/main/src/zenml/integrations) on our GitHub. ## Installing ZenML integrations Before you can use integrations, you first need to install them using `zenml integration install`, e.g., you can install [Kubeflow](orchestrators/kubeflow.md), [MLflow Tracking](experiment-trackers/mlflow.md), and [Seldon Core](model-deployers/seldon.md), using: ``` zenml integration install kubeflow mlflow seldon -y ``` Under the hood, this simply installs the preferred versions of all integrations using pip, i.e., it executes in a sub-process call: ``` pip install kubeflow== mlflow== seldon== ``` {% hint style="info" %} * The `-y` flag confirms all `pip install` commands without asking you for You can run `zenml integration --help` to see a full list of CLI commands that ZenML provides for interacting with integrations. {% endhint %} Note, that you can also install your dependencies directly, but please note that there is no guarantee that ZenML internals with work with any arbitrary version of any external library. ### Use `uv` for package installation You can use [`uv`](https://github.com/astral-sh/uv) as a package manager if you want. Simply pass the `--uv` flag to the `zenml integration ...` command and it'll use `uv` for installation, upgrades and uninstallations. Note that `uv` must be installed for this to work. This is an experimental option that we've added for users wishing to use `uv` but given that it is relatively new as an option there might be certain packages that don't work well with `uv`. We will monitor how this performs and update as `uv` becomes more stable. Full documentation for how it works with PyTorch can be found on Astral Docs website [here](https://docs.astral.sh/uv/guides/integration/pytorch/). It covers some of the particular gotchas and details you might need to know. ## Upgrade ZenML integrations You can upgrade all integrations to their latest possible version using: ```bash zenml integration upgrade mlflow pytorch -y ``` {% hint style="info" %} * The `-y` flag confirms all `pip install --upgrade` commands without asking you for confirmation. * If no integrations are specified, all installed integrations will be upgraded. {% endhint %} ## Help us with integrations! There are countless tools in the ML / MLOps field. We have made an initial prioritization of which tools to support with integrations that are visible on our public [roadmap](https://zenml.io/roadmap). We also welcome community contributions. Check our [Contribution Guide](https://github.com/zenml-io/zenml/blob/main/CONTRIBUTING.md) and [External Integration Guide](https://github.com/zenml-io/zenml/blob/main/src/zenml/integrations/README.md) for more details on how to best contribute to new integrations.
ZenML Scarf
================ File: docs/book/component-guide/README.md ================ --- icon: scroll description: Overview of categories of MLOps components and third-party integrations. --- # Overview If you are new to the world of MLOps, it is often daunting to be immediately faced with a sea of tools that seemingly all promise and do the same things. It is useful in this case to try to categorize tools in various groups in order to understand their value in your toolchain in a more precise manner. ZenML tackles this problem by introducing the concept of [Stacks and Stack Components](../user-guide/production-guide/understand-stacks.md). These stack components represent categories, each of which has a particular function in your MLOps pipeline. ZenML realizes these stack components as base abstractions that standardize the entire workflow for your team. In order to then realize the benefit, one can write a concrete implementation of the [abstraction](../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md), or use one of the many built-in [integrations](README.md) that implement these abstractions for you. Here is a full list of all stack components currently supported in ZenML, with a description of the role of that component in the MLOps process: | **Type of Stack Component** | **Description** | | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------- | | [Orchestrator](orchestrators/orchestrators.md) | Orchestrating the runs of your pipeline | | [Artifact Store](artifact-stores/artifact-stores.md) | Storage for the artifacts created by your pipelines | | [Container Registry](container-registries/container-registries.md) | Store for your containers | | [Data Validator](data-validators/data-validators.md) | Data and model validation | | [Experiment Tracker](experiment-trackers/experiment-trackers.md) | Tracking your ML experiments | | [Model Deployer](model-deployers/model-deployers.md) | Services/platforms responsible for online model serving | | [Step Operator](step-operators/step-operators.md) | Execution of individual steps in specialized runtime environments | | [Alerter](alerters/alerters.md) | Sending alerts through specified channels | | [Image Builder](image-builders/image-builders.md) | Builds container images. | | [Annotator](annotators/annotators.md) | Labeling and annotating data | | [Model Registry](model-registries/model-registries.md) | Manage and interact with ML Models | | [Feature Store](feature-stores/feature-stores.md) | Management of your data/features | Each pipeline run that you execute with ZenML will require a **stack** and each **stack** will be required to include at least an orchestrator and an artifact store. Apart from these two, the other components are optional and to be added as your pipeline evolves in MLOps maturity. ## Writing custom component flavors You can take control of how ZenML behaves by creating your own components. This is done by writing custom component `flavors`. To learn more, head over to [the general guide on writing component flavors](../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md), or read more specialized guides for specific component types (e.g. the [custom orchestrator guide](orchestrators/custom.md)). ## Integrations Categorizing the MLOps stack is a good way to write abstractions for an MLOps pipeline and standardize your processes. But ZenML goes further and also provides concrete implementations of these categories by **integrating** with various tools for each category. Once code is organized into a ZenML pipeline, you can supercharge your ML workflows with the best-in-class solutions from various MLOps areas. For example, you can orchestrate your ML pipeline workflows using [Airflow](orchestrators/airflow.md) or [Kubeflow](orchestrators/kubeflow.md), track experiments using [MLflow Tracking](experiment-trackers/mlflow.md) or [Weights & Biases](experiment-trackers/wandb.md), and transition seamlessly from a local [MLflow deployment](model-deployers/mlflow.md) to a deployed model on Kubernetes using [Seldon Core](model-deployers/seldon.md). There are lots of moving parts for all the MLOps tooling and infrastructure you require for ML in production and ZenML brings them all together and enables you to manage them in one place. This also allows you to delay the decision of which MLOps tool to use in your stack as you have no vendor lock-in with ZenML and can easily switch out tools as soon as your requirements change. ![ZenML is the glue](../../book/.gitbook/assets/zenml-is-the-glue.jpeg) ### Available integrations We have a [dedicated webpage](https://zenml.io/integrations) that indexes all supported ZenML integrations and their categories. Another easy way of seeing a list of integrations is to see the list of directories in the [integrations directory](https://github.com/zenml-io/zenml/tree/main/src/zenml/integrations) on our GitHub. ### Installing ZenML integrations Before you can use integrations, you first need to install them using `zenml integration install`, e.g., you can install [Kubeflow](orchestrators/kubeflow.md), [MLflow Tracking](experiment-trackers/mlflow.md), and [Seldon Core](model-deployers/seldon.md), using: ``` zenml integration install kubeflow mlflow seldon -y ``` Under the hood, this simply installs the preferred versions of all integrations using pip, i.e., it executes in a sub-process call: ``` pip install kubeflow== mlflow== seldon== ``` {% hint style="info" %} * The `-y` flag confirms all `pip install` commands without asking you for You can run `zenml integration --help` to see a full list of CLI commands that ZenML provides for interacting with integrations. {% endhint %} Note, that you can also install your dependencies directly, but please note that there is no guarantee that ZenML internals with work with any arbitrary version of any external library. #### Use `uv` for package installation You can use [`uv`](https://github.com/astral-sh/uv) as a package manager if you want. Simply pass the `--uv` flag to the `zenml integration ...` command and it'll use `uv` for installation, upgrades and uninstalls. Note that `uv` must be installed for this to work. This is an experimental option that we've added for users wishing to use `uv` but given that it is relatively new as an option there might be certain packages that don't work well with `uv`. Full documentation for how it works with PyTorch can be found on Astral's docs website [here](https://docs.astral.sh/uv/guides/integration/pytorch/). It covers some of the particular gotchas and details you might need to know. ### Upgrade ZenML integrations You can upgrade all integrations to their latest possible version using: ```bash zenml integration upgrade mlflow pytorch -y ``` {% hint style="info" %} * The `-y` flag confirms all `pip install --upgrade` commands without asking you for confirmation. * If no integrations are specified, all installed integrations will be upgraded. {% endhint %} ### Help us with integrations! There are countless tools in the ML / MLOps field. We have made an initial prioritization of which tools to support with integrations that are visible on our public [roadmap](https://zenml.io/roadmap). We also welcome community contributions. Check our [Contribution Guide](https://github.com/zenml-io/zenml/blob/main/CONTRIBUTING.md) and [External Integration Guide](https://github.com/zenml-io/zenml/blob/main/src/zenml/integrations/README.md) for more details on how to best contribute to new integrations.
ZenML Scarf