This file is a merged representation of the entire codebase, combining all repository files into a single document. Generated by Repomix on: 2025-01-30T10:25:41.954Z ================================================================ 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 getting-started/ deploying-zenml/ custom-secret-stores.md deploy-using-huggingface-spaces.md deploy-with-custom-image.md README.md secret-management.md zenml-pro/ core-concepts.md organization.md pro-api.md README.md roles.md teams.md tenants.md core-concepts.md installation.md system-architectures.md how-to/ advanced-topics/ README.md configuring-zenml/ configuring-zenml.md contribute-to-zenml/ implement-a-custom-integration.md README.md control-logging/ disable-colorful-logging.md disable-rich-traceback.md enable-or-disable-logs-storing.md README.md set-logging-verbosity.md view-logs-on-the-dasbhoard.md customize-docker-builds/ define-where-an-image-is-built.md docker-settings-on-a-pipeline.md docker-settings-on-a-step.md how-to-reuse-builds.md how-to-use-a-private-pypi-repository.md README.md specify-pip-dependencies-and-apt-packages.md use-a-prebuilt-image.md use-your-own-docker-files.md which-files-are-built-into-the-image.md data-artifact-management/ complex-usecases/ datasets.md manage-big-data.md passing-artifacts-between-pipelines.md README.md registering-existing-data.md unmaterialized-artifacts.md handle-data-artifacts/ artifact-versioning.md artifacts-naming.md delete-an-artifact.md get-arbitrary-artifacts-in-a-step.md handle-custom-data-types.md load-artifacts-into-memory.md README.md return-multiple-outputs-from-a-step.md tagging.md visualize-artifacts/ creating-custom-visualizations.md disabling-visualizations.md README.md types-of-visualizations.md visualizations-in-dashboard.md README.md infrastructure-deployment/ auth-management/ aws-service-connector.md azure-service-connector.md best-security-practices.md docker-service-connector.md gcp-service-connector.md hyperai-service-connector.md kubernetes-service-connector.md README.md service-connectors-guide.md infrastructure-as-code/ best-practices.md README.md terraform-stack-management.md stack-deployment/ deploy-a-cloud-stack-with-terraform.md deploy-a-cloud-stack.md export-stack-requirements.md implement-a-custom-stack-component.md README.md reference-secrets-in-stack-configuration.md register-a-cloud-stack.md README.md manage-zenml-server/ connecting-to-zenml/ connect-in-with-your-user-interactive.md connect-with-a-service-account.md README.md migration-guide/ migration-guide.md migration-zero-forty.md migration-zero-sixty.md migration-zero-thirty.md migration-zero-twenty.md best-practices-upgrading-zenml.md README.md troubleshoot-your-deployed-server.md upgrade-zenml-server.md using-zenml-server-in-prod.md model-management-metrics/ model-control-plane/ associate-a-pipeline-with-a-model.md connecting-artifacts-via-a-model.md delete-a-model.md linking-model-binaries-data-to-models.md load-a-model-in-code.md load-artifacts-from-model.md model-versions.md promote-a-model.md README.md register-a-model.md track-metrics-metadata/ attach-metadata-to-a-model.md attach-metadata-to-a-run.md attach-metadata-to-a-step.md attach-metadata-to-an-artifact.md fetch-metadata-within-pipeline.md fetch-metadata-within-steps.md grouping-metadata.md logging-metadata.md README.md README.md pipeline-development/ build-pipelines/ access-secrets-in-a-step.md compose-pipelines.md configuring-a-pipeline-at-runtime.md control-caching-behavior.md control-execution-order-of-steps.md delete-a-pipeline.md fan-in-fan-out.md fetching-pipelines.md get-past-pipeline-step-runs.md hyper-parameter-tuning.md name-your-pipeline-runs.md README.md reference-environment-variables-in-configurations.md retry-steps.md run-an-individual-step.md run-pipelines-asynchronously.md schedule-a-pipeline.md step-output-typing-and-annotation.md tag-your-pipeline-runs.md use-failure-success-hooks.md use-pipeline-step-parameters.md using-a-custom-step-invocation-id.md configure-python-environments/ configure-the-server-environment.md handling-dependencies.md README.md develop-locally/ keep-your-dashboard-server-clean.md local-prod-pipeline-variants.md README.md run-remote-notebooks/ limitations-of-defining-steps-in-notebook-cells.md README.md run-a-single-step-from-a-notebook.md training-with-gpus/ accelerate-distributed-training.md README.md use-configuration-files/ autogenerate-a-template-yaml-file.md configuration-hierarchy.md how-to-use-config.md README.md retrieve-used-configuration-of-a-run.md runtime-configuration.md what-can-be-configured.md README.md popular-integrations/ aws-guide.md azure-guide.md gcp-guide.md kubeflow.md kubernetes.md mlflow.md README.md skypilot.md project-setup-and-management/ collaborate-with-team/ project-templates/ create-your-own-template.md README.md access-management.md README.md shared-components-for-teams.md stacks-pipelines-models.md setting-up-a-project-repository/ connect-your-git-repository.md README.md set-up-repository.md interact-with-secrets.md README.md trigger-pipelines/ README.md use-templates-cli.md use-templates-dashboard.md use-templates-python.md use-templates-rest-api.md debug-and-solve-issues.md reference/ api-reference.md community-and-content.md environment-variables.md faq.md global-settings.md how-do-i.md python-client.md user-guide/ cloud-guide/ cloud-guide.md llmops-guide/ evaluation/ evaluation-in-65-loc.md evaluation-in-practice.md generation.md README.md retrieval.md finetuning-embeddings/ evaluating-finetuned-embeddings.md finetuning-embeddings-with-sentence-transformers.md finetuning-embeddings.md synthetic-data-generation.md finetuning-llms/ deploying-finetuned-models.md evaluation-for-finetuning.md finetuning-100-loc.md finetuning-llms.md finetuning-with-accelerate.md next-steps.md starter-choices-for-finetuning-llms.md why-and-when-to-finetune-llms.md rag-with-zenml/ basic-rag-inference-pipeline.md data-ingestion.md embeddings-generation.md rag-85-loc.md README.md storing-embeddings-in-a-vector-database.md understanding-rag.md reranking/ evaluating-reranking-performance.md implementing-reranking.md README.md reranking.md understanding-reranking.md README.md production-guide/ ci-cd.md cloud-orchestration.md configure-pipeline.md connect-code-repository.md deploying-zenml.md end-to-end.md README.md remote-storage.md understand-stacks.md starter-guide/ cache-previous-executions.md create-an-ml-pipeline.md manage-artifacts.md README.md starter-project.md track-ml-models.md introduction.md toc.md ================================================================ Files ================================================================ ================ File: docs/book/component-guide/alerters/alerters.md ================ --- description: Sending automated alerts to chat services. icon: message-exclamation --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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 --- # 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 --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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 --- # 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 --- # 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 --- # 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 --- # 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. --- # 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. --- # 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. --- # 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 --- # 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. --- # 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 --- # 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. --- # 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. --- # 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. --- # 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. --- # 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 --- # 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. --- # 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 --- # 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. --- # 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. --- # 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. --- # 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. --- # 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 --- # 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:. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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 --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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. --- # 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 --- ``` 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. --- # 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. --- # 📜 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. --- # 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
================ File: docs/book/getting-started/deploying-zenml/custom-secret-stores.md ================ --- description: Learning how to develop a custom secret store. --- # Custom secret stores The secrets store acts as the one-stop shop for all the secrets to which your pipeline or stack components might need access. It is responsible for storing, updating and deleting _only the secrets values_ for ZenML secrets, while the ZenML secret metadata is stored in the SQL database. The secrets store interface implemented by all available secrets store back-ends is defined in the `zenml.zen_stores.secrets_stores.secrets_store_interface` core module and looks more or less like this: ```python class SecretsStoreInterface(ABC): """ZenML secrets store interface. All ZenML secrets stores must implement the methods in this interface. """ # --------------------------------- # Initialization and configuration # --------------------------------- @abstractmethod def _initialize(self) -> None: """Initialize the secrets store. This method is called immediately after the secrets store is created. It should be used to set up the backend (database, connection etc.). """ # --------- # Secrets # --------- @abstractmethod def store_secret_values( self, secret_id: UUID, secret_values: Dict[str, str], ) -> None: """Store secret values for a new secret. Args: secret_id: ID of the secret. secret_values: Values for the secret. """ @abstractmethod def get_secret_values(self, secret_id: UUID) -> Dict[str, str]: """Get the secret values for an existing secret. Args: secret_id: ID of the secret. Returns: The secret values. Raises: KeyError: if no secret values for the given ID are stored in the secrets store. """ @abstractmethod def update_secret_values( self, secret_id: UUID, secret_values: Dict[str, str], ) -> None: """Updates secret values for an existing secret. Args: secret_id: The ID of the secret to be updated. secret_values: The new secret values. Raises: KeyError: if no secret values for the given ID are stored in the secrets store. """ @abstractmethod def delete_secret_values(self, secret_id: UUID) -> None: """Deletes secret values for an existing secret. Args: secret_id: The ID of the secret. Raises: KeyError: if no secret values for the given ID are stored in the secrets store. """ ``` {% hint style="info" %} This is a slimmed-down version of the real interface which aims to highlight the abstraction layer. In order to see the full definition and get the complete docstrings, please check the [SDK docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-zen\_stores/#zenml.zen\_stores.secrets\_stores.secrets\_store\_interface.SecretsStoreInterface) . {% endhint %} ## Build your own custom secrets store If you want to create your own custom secrets store implementation, you can follow the following steps: 1. Create a class that inherits from the `zenml.zen_stores.secrets_stores.base_secrets_store.BaseSecretsStore` base class and implements the `abstractmethod`s shown in the interface above. Use `SecretsStoreType.CUSTOM` as the `TYPE` value for your secrets store class. 2. If you need to provide any configuration, create a class that inherits from the `SecretsStoreConfiguration` class and add your configuration parameters there. Use that as the `CONFIG_TYPE` value for your secrets store class. 3. To configure the ZenML server to use your custom secrets store, make sure your code is available in the container image that is used to run the ZenML server. Then, use environment variables or helm chart values to configure the ZenML server to use your custom secrets store, as covered in the [deployment guide](./README.md).
ZenML Scarf
================ File: docs/book/getting-started/deploying-zenml/deploy-using-huggingface-spaces.md ================ --- description: Deploying ZenML to Huggingface Spaces. --- # Deploy using HuggingFace Spaces A quick way to deploy ZenML and get started is to use [HuggingFace Spaces](https://huggingface.co/spaces). HuggingFace Spaces is a platform for hosting and sharing ML projects and workflows, and it also works to deploy ZenML. You can be up and running in minutes (for free) with a hosted ZenML server, so it's a good option if you want to try out ZenML without any infrastructure overhead. {% hint style="info" %} If you are planning to use HuggingFace Spaces for production use, make sure you have [persistent storage turned on](https://huggingface.co/docs/hub/en/spaces-storage) so as to prevent loss of data. See our [other deployment options](./README.md) if you want alternative options. {% endhint %} ![ZenML on HuggingFace Spaces -- default deployment](../../.gitbook/assets/hf-spaces-chart.png) In this diagram, you can see what the default deployment of ZenML on HuggingFace looks like. ## Deploying ZenML on HuggingFace Spaces You can deploy ZenML on HuggingFace Spaces with just a few clicks: [![](https://huggingface.co/datasets/huggingface/badges/raw/main/deploy-to-spaces-lg.svg)](https://huggingface.co/new-space?template=zenml/zenml) To set up your ZenML app, you need to specify three main components: the Owner (either your personal account or an organization), a Space name, and the Visibility (a bit lower down the page). Note that the space visibility needs to be set to 'Public' if you wish to connect to the ZenML server from your local machine. ![HuggingFace Spaces SDK interface](../../.gitbook/assets/hf-spaces-sdk.png) You have the option here to select a higher-tier machine to use for your server. The advantage of selecting a paid CPU instance is that it is not subject to auto-shutdown policies and thus will stay up as long as you leave it up. In order to make use of a persistent CPU, you'll likely want to create and set up a MySQL database to connect to (see below). To personalize your Space's appearance, such as the title, emojis, and colors, navigate to "Files and Versions" and modify the metadata in your README.md file. Full information on Spaces configuration parameters can be found on the HuggingFace [documentation reference guide](https://huggingface.co/docs/hub/spaces-config-reference). After creating your Space, you'll notice a 'Building' status along with logs displayed on the screen. When this switches to 'Running', your Space is ready for use. If the ZenML login UI isn't visible, try refreshing the page. In the upper-right hand corner of your space you'll see a button with three dots which, when you click on it, will offer you a menu option to "Embed this Space". (See [the HuggingFace documentation](https://huggingface.co/docs/hub/spaces-embed) for more details on this feature.) Copy the "Direct URL" shown in the box that you can now see on the screen. This should look something like this: `https://-.hf.space`. Open that URL and follow the instructions to initialize your ZenML server and set up an initial admin user account. ## Connecting to your ZenML Server from your local machine Once you have your ZenML server up and running, you can connect to it from your local machine. To do this, you'll need to get your Space's 'Direct URL' (see above). {% hint style="warning" %} Your Space's URL will only be available and usable for connecting from your local machine if the visibility of the space is set to 'Public'. {% endhint %} You can use the 'Direct URL' to connect to your ZenML server from your local machine with the following CLI command (after installing ZenML, and using your custom URL instead of the placeholder): ```shell zenml login '' ``` You can also use the Direct URL in your browser to use the ZenML dashboard as a fullscreen application (i.e. without the HuggingFace Spaces wrapper around it). ## Extra configuration options By default, the ZenML application will be configured to use an SQLite non-persistent database. If you want to use a persistent database, you can configure this by amending the `Dockerfile` to your Space's root directory. For full details on the various parameters you can change, see [our reference documentation](deploy-with-docker.md#advanced-server-configuration-options) on configuring ZenML when deployed with Docker. {% hint style="info" %} If you are using the space just for testing and experimentation, you don't need to make any changes to the configuration. Everything will work out of the box. {% endhint %} You can also use an external secrets backend together with your HuggingFace Spaces as described in [our documentation](deploy-with-docker.md#advanced-server-configuration-options). You should be sure to use HuggingFace's inbuilt ' Repository secrets' functionality to configure any secrets you need to use in your`Dockerfile` configuration. [See the documentation](https://huggingface.co/docs/hub/spaces-sdks-docker#secret-management) for more details on how to set this up. {% hint style="warning" %} If you wish to use a cloud secrets backend together with ZenML for secrets management, **you must update your password** on your ZenML Server on the Dashboard. This is because the default user created by the HuggingFace Spaces deployment process has no password assigned to it and as the Space is publicly accessible (since the Space is public) _potentially anyone could access your secrets without this extra step_. To change your password navigate to the Settings page by clicking the button in the upper right-hand corner of the Dashboard and then click 'Update Password'. {% endhint %} ## Troubleshooting If you are having trouble with your ZenML server on HuggingFace Spaces, you can view the logs by clicking on the "Open Logs" button at the top of the space. This will give you more context of what's happening with your server. If you have any other issues, please feel free to reach out to us on our [Slack channel](https://zenml.io/slack/) for more support. ## Upgrading your ZenML Server on HF Spaces The default space will use the latest version of ZenML automatically. If you want to update your version, you can simply select the 'Factory reboot' option within the 'Settings' tab of the space. Note that this will wipe any data contained within the space and so if you are not using a MySQL persistent database (as described above) you will lose any data contained within your ZenML deployment on the space. You can also configure the space to use an earlier version by updating the `Dockerfile`'s `FROM` import statement at the very top.
ZenML Scarf
================ File: docs/book/getting-started/deploying-zenml/deploy-with-custom-image.md ================ --- description: Deploying ZenML with custom Docker images. --- # Deploy with custom images In most cases, deploying ZenML with the default `zenmlhub/zenml-server` Docker image should work just fine. However, there are some scenarios when you might need to deploy ZenML with a custom Docker image: * You have implemented a custom artifact store for which you want to enable [artifact visualizations](../../how-to/data-artifact-management/visualize-artifacts/README.md) or [step logs](../../../how-to/setting-up-a-project-repository/best-practices.md#logging) in your dashboard. * You have forked the ZenML repository and want to deploy a ZenML server based on your own fork because you made changes to the server / database logic. {% hint style="warning" %} Deploying ZenML with custom Docker images is only possible for [Docker](deploy-with-docker.md) or [Helm](deploy-with-helm.md) deployments. {% endhint %} ### Build and Push Custom ZenML Server Docker Image Here is how you can build a custom ZenML server Docker image: 1. Set up a container registry of your choice. E.g., as an indivial developer you could create a free [Docker Hub](https://hub.docker.com/) account and then set up a free Docker Hub repository. 2. Clone ZenML (or your ZenML fork) and checkout the branch that you want to deploy, e.g., if you want to deploy ZenML version 0.41.0, run ```bash git checkout release/0.41.0 ``` 3. Copy the [ZenML base.Dockerfile](https://github.com/zenml-io/zenml/blob/main/docker/base.Dockerfile), e.g.: ```bash cp docker/base.Dockerfile docker/custom.Dockerfile ``` 4. Modify the copied Dockerfile: * Add additional dependencies: ```bash RUN pip install ``` * (Forks only) install local files instead of official ZenML: ```bash RUN pip install -e .[server,secrets-aws,secrets-gcp,secrets-azure,secrets-hashicorp,s3fs,gcsfs,adlfs,connectors-aws,connectors-gcp,connectors-azure] ``` 5. Build and push an image based on your Dockerfile: ```bash docker build -f docker/custom.Dockerfile . -t /: --platform linux/amd64 docker push /: ``` {% hint style="info" %} If you want to verify your custom image locally, you can follow the [Deploy a custom ZenML image via Docker](deploy-with-custom-image.md#deploy-a-custom-zenml-image-via-docker) section below to deploy the ZenML server locally first. {% endhint %} ### Deploy ZenML with your custom image Next, adjust your preferred deployment strategy to use the custom Docker image you just built. #### Deploy a custom ZenML image via Docker To deploy your custom image via Docker, first familiarize yourself with the general [ZenML Docker Deployment Guide](deploy-with-docker.md). To use your own image, follow the general guide step by step but replace all mentions of `zenmldocker/zenml-server` with your custom image reference `/:`. E.g.: * To run the ZenML server with Docker based on your custom image, do ```bash docker run -it -d -p 8080:8080 --name zenml /: ``` * To use `docker-compose`, adjust your `docker-compose.yml`: ```yaml services: zenml: image: /: ``` #### Deploy a custom ZenML image via Helm To deploy your custom image via Helm, first familiarize yourself with the general [ZenML Helm Deployment Guide](deploy-with-helm.md). To use your own image, the only thing you need to do differently is to modify the `image` section of your `values.yaml` file: ```yaml zenml: image: repository: / tag: ```
ZenML Scarf
================ File: docs/book/getting-started/deploying-zenml/README.md ================ --- icon: rocket-launch description: Why do we need to deploy ZenML? --- # Deploying ZenML ![ZenML OSS server deployment architecture](../../.gitbook/assets/oss_simple_deployment.png) Moving your ZenML Server to a production environment offers several benefits over staying local: 1. **Scalability**: Production environments are designed to handle large-scale workloads, allowing your models to process more data and deliver faster results. 2. **Reliability**: Production-grade infrastructure ensures high availability and fault tolerance, minimizing downtime and ensuring consistent performance. 3. **Collaboration**: A shared production environment enables seamless collaboration between team members, making it easier to iterate on models and share insights. Despite these advantages, transitioning to production can be challenging due to the complexities involved in setting up the needed infrastructure. ## Components A ZenML deployment consists of multiple infrastructure components: - [FastAPI server](https://github.com/zenml-io/zenml/tree/main/src/zenml/zen_server) backed with a SQLite or MySQL database - [Python Client](https://github.com/zenml-io/zenml/tree/main/src/zenml) - An [open-source companion ReactJS](https://github.com/zenml-io/zenml-dashboard) dashboard - (Optional) [ZenML Pro API + Database + ZenML Pro dashboard](../system-architectures.md) You can read more in-depth about the system architecture of ZenML [here](../system-architectures.md). This documentation page will focus on the components required to deploy ZenML OSS.
Details on the ZenML Python Client The ZenML client is a Python package that you can install on your machine. It is used to interact with the ZenML server. You can install it using the `pip` command as outlined [here](../installation.md). This Python package gives you [the `zenml` command-line interface](https://sdkdocs.zenml.io/latest/cli/) which you can use to interact with the ZenML server for common tasks like managing stacks, setting up secrets, and so on. It also gives you the general framework that lets you [author and deploy pipelines](../../user-guide/starter-guide/README.md) and so forth. If you want to have more fine-grained control and access to the metadata that ZenML manages, you can use the Python SDK to access the API. This allows you to create your own custom automations and scripts and is the most common way teams access the metadata stored in the ZenML server. The full documentation for the Python SDK can be found [here](https://sdkdocs.zenml.io/latest/). The full HTTP [API documentation](../../reference/api-reference.md) can also be found by adding the `/doc` suffix to the URL when accessing your deployed ZenML server.
### Deployment scenarios When you first get started with ZenML, you have the following architecture on your machine. ![ZenML default local configuration](../../.gitbook/assets/Scenario1.png) The SQLite database that you can see in this diagram is used to store information about pipelines, pipeline runs, stacks, and other configurations. This default setup allows you to get started and try out the core features but you won't be able to use cloud-based components like serverless orchestrators and so on. Users can run the `zenml login --local` command to spin up a local ZenML OSS server to serve the dashboard. For the local OSS server option, the `zenml login --local` command implicitly connects the client to the server. The diagram for this looks as follows: ![ZenML with a local ZenML OSS Server](../../.gitbook/assets/Scenario2.png) In order to move into production, the ZenML server needs to be deployed somewhere centrally so that the different cloud stack components can read from and write to the server. Additionally, this also allows all your team members to connect to it and share stacks and pipelines. ![ZenML centrally deployed for multiple users](../../.gitbook/assets/Scenario3.2.png) You connect to your deployed ZenML server using the `zenml login` command and then you have the full benefits and power of ZenML. You can use all the cloud-based components, your metadata will be stored and synchronized across all the users of the server and you can leverage features like centralized logs storage and pipeline artifact visualization. ## How to deploy ZenML Deploying the ZenML Server is a crucial step towards transitioning to a production-grade environment for your machine learning projects. By setting up a deployed ZenML Server instance, you gain access to powerful features, allowing you to use stacks with remote components, centrally track progress, collaborate effectively, and achieve reproducible results. Currently, there are two main options to access a deployed ZenML server: 1. **Managed deployment:** With [ZenML Pro](../zenml-pro/README.md) offering you can utilize a control plane to create ZenML servers, also known as [tenants](../zenml-pro/tenants.md). These tenants are managed and maintained by ZenML's dedicated team, alleviating the burden of server management from your end. Importantly, your data remains securely within your stack, and ZenML's role is primarily to handle tracking of metadata and server maintenance. 2. **Self-hosted Deployment:** Alternatively, you have the ability to deploy ZenML on your own self-hosted environment. This can be achieved through various methods, including using [Docker](./deploy-with-docker.md), [Helm](./deploy-with-helm.md), or [HuggingFace Spaces](./deploy-using-huggingface-spaces.md). We also offer our Pro version for self-hosted deployments, so you can use our full paid feature-set while staying fully in control with an air-gapped solution on your infrastructure. Both options offer distinct advantages, allowing you to choose the deployment approach that best aligns with your organization's needs and infrastructure preferences. Whichever path you select, ZenML facilitates a seamless and efficient way to take advantage of the ZenML Server and enhance your machine learning workflows for production-level success. ### Options for deploying ZenML Documentation for the various deployment strategies can be found in the following pages below (in our 'how-to' guides):
Deploying ZenML using ZenML ProDeploying ZenML using ZenML Pro.deploy-with-zenml-cli.md
Deploy with DockerDeploying ZenML in a Docker container.deploy-with-docker.md
Deploy with HelmDeploying ZenML in a Kubernetes cluster with Helm.deploy-with-helm.md
Deploy with HuggingFace SpacesDeploying ZenML to Hugging Face Spaces.deploy-with-hugging-face-spaces.md
ZenML Scarf
================ File: docs/book/getting-started/deploying-zenml/secret-management.md ================ --- description: Configuring the secrets store. --- # Secret store configuration and management ## Centralized secrets store ZenML provides a centralized secrets management system that allows you to register and manage secrets in a secure way. The metadata of the ZenML secrets (e.g. name, ID, owner, scope etc.) is always stored in the ZenML server database, while the actual secret values are stored and managed separately, through the ZenML Secrets Store. This allows for a flexible deployment strategy that meets the security and compliance requirements of your organization. In a local ZenML deployment, secret values are also stored in the local SQLite database. When connected to a remote ZenML server, the secret values are stored in the secrets management back-end that the server's Secrets Store is configured to use, while all access to the secrets is done through the ZenML server API.

Basic Secrets Store Architecture

Currently, the ZenML server can be configured to use one of the following supported secrets store back-ends: * the same SQL database that the ZenML server is using to store secrets metadata as well as other managed objects such as pipelines, stacks, etc. This is the default option. * the AWS Secrets Manager * the GCP Secret Manager * the Azure Key Vault * the HashiCorp Vault * a custom secrets store back-end implementation is also supported ## Configuration and deployment Configuring the specific secrets store back-end that the ZenML server uses is done at deployment time. This involves deciding on one of the supported back-ends and authentication mechanisms and configuring the ZenML server with the necessary credentials to authenticate with the back-end. The ZenML secrets store reuses the [ZenML Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) authentication mechanisms to authenticate with the secrets store back-end. This means that the same authentication methods and configuration parameters that are supported by the available Service Connectors are also reflected in the ZenML secrets store configuration. It is recommended to practice the principle of least privilege when configuring the ZenML secrets store and to use credentials with the documented minimum required permissions to access the secrets store back-end. The ZenML secrets store configured for the ZenML Server can be updated at any time by updating the ZenML Server configuration and redeploying the server. This allows you to easily switch between different secrets store back-ends and authentication mechanisms. However, it is recommended to follow [the documented secret store migration strategy](secret-management.md#secrets-migration-strategy) to minimize downtime and to ensure that existing secrets are also properly migrated, in case the location where secrets are stored in the back-end changes. For more information on how to deploy a ZenML server and configure the secrets store back-end, refer to your deployment strategy inside the deployment guide. ## Backup secrets store The ZenML Server deployment may be configured to optionally connect to _a second Secrets Store_ to provide additional features such as high-availability, backup and disaster recovery as well as an intermediate step in the process of migrating [secrets from one secrets store location to another](secret-management.md#secrets-migration-strategy). For example, the primary Secrets Store may be configured to use the internal database, while the backup Secrets Store may be configured to use the AWS Secrets Manager. Or two different AWS Secrets Manager accounts or regions may be used. {% hint style="warning" %} Always make sure that the backup Secrets Store is configured to use a different location than the primary Secrets Store. The location can be different in terms of the Secrets Store back-end type (e.g. internal database vs. AWS Secrets Manager) or the actual location of the Secrets Store back-end (e.g. different AWS Secrets Manager account or region, GCP Secret Manager project or Azure Key Vault's vault). Using the same location for both the primary and backup Secrets Store will not provide any additional benefits and may even result in unexpected behavior. {% endhint %} When a backup secrets store is in use, the ZenML Server will always attempt to read and write secret values from/to the primary Secrets Store first while ensuring to keep the backup Secrets Store in sync. If the primary Secrets Store is unreachable, if the secret values are not found there or any otherwise unexpected error occurs, the ZenML Server falls back to reading and writing from/to the backup Secrets Store. Only if the backup Secrets Store is also unavailable, the ZenML Server will return an error. In addition to the hidden backup operations, users can also explicitly trigger a backup operation by using the `zenml secret backup` CLI command. This command will attempt to read all secrets from the primary Secrets Store and write them to the backup Secrets Store. Similarly, the `zenml secret restore` CLI command can be used to restore secrets from the backup Secrets Store to the primary Secrets Store. These CLI commands are useful for migrating secrets from one Secrets Store to another. ## Secrets migration strategy Sometimes you may need to change the external provider or location where secrets values are stored by the Secrets Store. The immediate implication of this is that the ZenML server will no longer be able to access existing secrets with the new configuration until they are also manually copied to the new location. Some examples of such changes include: * switching Secrets Store back-end types (e.g. from internal SQL database to AWS Secrets Manager or Azure Key Vault) * switching back-end locations (e.g. changing the AWS Secrets Manager account or region, GCP Secret Manager project or Azure Key Vault's vault). In such cases, it is not sufficient to simply reconfigure and redeploy the ZenML server with the new Secrets Store configuration. This is because the ZenML server will not automatically migrate existing secrets to the new location. Instead, you should follow a specific migration strategy to ensure that existing secrets are also properly migrated to the new location with minimal, even zero downtime. The secrets migration process makes use of the fact that [a secondary Secrets Store](secret-management.md#backup-secrets-store) can be configured for the ZenML server for backup purposes. This secondary Secrets Store is used as an intermediate step in the migration process. The migration process is as follows (we'll refer to the Secrets Store that is currently in use as _Secrets Store A_ and the Secrets Store that will be used after the migration as _Secrets Store B_): 1. Re-configure the ZenML server to use _Secrets Store B_ as the secondary Secrets Store. 2. Re-deploy the ZenML server. 3. Use the `zenml secret backup` CLI command to back up all secrets from _Secrets Store A_ to _Secrets Store B_. You don't have to worry about secrets that are created or updated by users during or after this process, as they will be automatically backed up to _Secrets Store B_. If you also wish to delete secrets from _Secrets Store A_ after they are successfully backed up to _Secrets Store B_, you should run `zenml secret backup --delete-secrets` instead. 4. Re-configure the ZenML server to use _Secrets Store B_ as the primary Secrets Store and remove _Secrets Store A_ as the secondary Secrets Store. 5. Re-deploy the ZenML server. This migration strategy is not necessary if the actual location of the secrets values in the Secrets Store back-end does not change. For example: * updating the credentials used to authenticate with the Secrets Store back-end before or after they expire * switching to a different authentication method to authenticate with the same Secrets Store back-end (e.g. switching from an IAM account secret key to an IAM role in the AWS Secrets Manager) If you are a [ZenML Pro](https://zenml.io/pro) user, you can configure your cloud backend based on your [deployment scenario](../system-architectures.md).
ZenML Scarf
================ File: docs/book/getting-started/zenml-pro/core-concepts.md ================ # ZenML Pro Core Concepts In ZenML Pro, there is a slightly different entity hierarchy as compared to the open-source ZenML framework. This document walks you through the key differences and new concepts that are only available for Pro users. ![Image showing the entity hierarchy in ZenML Pro](../../.gitbook/assets/org_hierarchy_pro.png) The image above shows the hierarchy of concepts in ZenML Pro. - At the top level is your [**Organization**](./organization.md). An organization is a collection of users, teams, and tenants. - Each [**Tenant**](./tenants.md) is an isolated deployment of a ZenML server. It contains all the resources for your project or team. - [**Teams**](./teams.md) are groups of users within an organization. They help in organizing users and managing access to resources. - **Users** are single individual accounts on a ZenML Pro instance. - [**Roles**](./roles.md) are used to control what actions users can perform within a tenant or inside an organization. - [**Templates**](../../how-to/trigger-pipelines/README.md) are pipeline runs that can be re-run with a different configuration. More details about each of these concepts are available in their linked pages below:
OrganizationsLearn about managing organizations in ZenML Pro.organization.md
TenantsUnderstand how to work with tenants in ZenML Pro.tenants.md
TeamsExplore team management in ZenML Pro.teams.md
Roles & PermissionsLearn about role-based access control in ZenML Pro.roles.md
ZenML Scarf
================ File: docs/book/getting-started/zenml-pro/organization.md ================ # Organizations ZenML Pro arranges various aspects of your work experience around the concept of an **Organization**. This is the top-most level structure within the ZenML Cloud environment. Generally, an organization contains a group of users and one or more [tenants](./tenants.md). ## Inviting Team Members to Your Organization Inviting users to your organization to work on the organization's tenants is easy. Simply click `Add Member` in the Organization settings, and give them an initial Role. The user will be sent an invitation email. If a user is part of an organization, they can utilize their login on all tenants they have authority to access. ![Image showing invite flow](../../.gitbook/assets/add_org_members.png) ## Manage Organization settings like billing and roles The billing information for your tenants is managed on the organization level, among other settings like the members in your organization and the roles they have. You can access the organization settings by clicking on your profile picture in the top right corner and selecting "Settings". ![Image showing the organization settings page](../../.gitbook/assets/org_settings.png) ## Other operations involving organizations There are a lot of other operations involving Organizations that you can perform directly through the API. You can find more information about the API by visiting [https://cloudapi.zenml.io/](https://cloudapi.zenml.io/). ![Image showing the Swagger docs](../../.gitbook/assets/cloudapi_swagger.png)
ZenML Scarf
================ File: docs/book/getting-started/zenml-pro/pro-api.md ================ --- description: > Learn how to use the ZenML Pro API. --- # Using the ZenML Pro API ZenML Pro offers a powerful API that allows you to interact with your ZenML resources. Whether you're using the [SaaS version](https://cloud.zenml.io) or a self-hosted ZenML Pro instance, you can leverage this API to manage tenants, organizations, users, roles, and more. The SaaS version of ZenML Pro API is hosted at [https://cloudapi.zenml.io](https://cloudapi.zenml.io). ## API Overview The ZenML Pro API is a RESTful API that follows OpenAPI 3.1.0 specifications. It provides endpoints for various resources and operations, including: - Tenant management - Organization management - User management - Role-based access control (RBAC) - Authentication and authorization ## Authentication To use the ZenML Pro API, you need to authenticate your requests. If you are logged in to your ZenML Pro account, you can use the same browser window to authenticate requests to your ZenML Pro API, directly in the OpenAPI docs. For example, for the SaaS variant, you can access the docs here: [https://cloudapi.zenml.io](https://cloudapi.zenml.io). You can make requests by being logged into ZenML Pro at [https://cloud.zenml.io](https://cloud.zenml.io). Programmatic access is not possible at the moment. ## Key API Endpoints Here are some important endpoints you can use with the ZenML Pro API: ### Tenant Management - List tenants: `GET /tenants` - Create a tenant: `POST /tenants` - Get tenant details: `GET /tenants/{tenant_id}` - Update a tenant: `PATCH /tenants/{tenant_id}` ### Organization Management - List organizations: `GET /organizations` - Create an organization: `POST /organizations` - Get organization details: `GET /organizations/{organization_id}` - Update an organization: `PATCH /organizations/{organization_id}` ### User Management - List users: `GET /users` - Get current user: `GET /users/me` - Update user: `PATCH /users/{user_id}` ### Role-Based Access Control - Create a role: `POST /roles` - Assign a role: `POST /roles/{role_id}/assignments` - Check permissions: `GET /permissions` ## Error Handling The API uses standard HTTP status codes to indicate the success or failure of requests. In case of errors, the response body will contain more details about the error, including a message and sometimes additional information. ## Rate Limiting Be aware that the ZenML Pro API may have rate limiting in place to ensure fair usage. If you exceed the rate limit, you may receive a 429 (Too Many Requests) status code. Implement appropriate backoff and retry logic in your applications to handle this scenario. Remember to refer to the complete API documentation available at [https://cloudapi.zenml.io](https://cloudapi.zenml.io) for detailed information about all available endpoints, request/response schemas, and additional features.
ZenML Scarf
================ File: docs/book/getting-started/zenml-pro/README.md ================ --- icon: cloud description: Learn about the ZenML Pro features and deployment scenarios. --- # ZenML Pro ![Walkthrough of ZenML Model Control Plane](../../.gitbook/assets/mcp_walkthrough.gif) The [Pro version of ZenML](https://zenml.io/pro) comes with a number of features that expand the functionality of the Open Source product. ZenML Pro adds a managed control plane with benefits like: - **A managed production-grade ZenML deployment**: With ZenML Pro you can deploy multiple ZenML servers called [tenants](./tenants.md). - **User management with teams**: Create [organizations](./organization.md) and [teams](./teams.md) to easily manage users at scale. - **Role-based access control and permissions**: Implement fine-grained access control using customizable [roles](./roles.md) to ensure secure and efficient resource management. - **Enhanced model and artifact control plane**: Leverage the [Model Control Plane](../../user-guide/starter-guide/track-ml-models.md) and [Artifact Control Plane](../../user-guide/starter-guide/manage-artifacts.md) for improved tracking and management of your ML assets. - **Triggers and run templates**: ZenML Pro enables you to [create and run templates](../../how-to/trigger-pipelines/README.md#run-templates). This way, you can use the dashboard or our Client/REST API to run a pipeline with updated configuration, allowing you to iterate quickly with minimal friction. - **Early-access features**: Get early access to pro-specific features such as triggers, filters, sorting, generating usage reports, and more. Learn more about ZenML Pro on the [ZenML website](https://zenml.io/pro). {% hint style="info" %} If you're interested in assessing ZenML Pro, you can simply create a [free account](https://cloud.zenml.io/?utm\_source=docs\&utm\_medium=referral\_link\&utm\_campaign=cloud\_promotion\&utm\_content=signup\_link). Learn more about ZenML Pro on the [ZenML website](https://zenml.io/pro). {% endhint %} ## Deployment scenarios: SaaS vs Self-hosted One of the most straightforward paths to start with a deployed ZenML server is to use [the SaaS version of ZenML Pro](https://zenml.io/pro). The ZenML Pro offering eliminates the need for you to dedicate time and resources to deploy and manage a ZenML server, allowing you to focus primarily on your MLOps workflows. However, ZenML Pro can also be deployed fully self-hosted. Please [book a demo](https://www.zenml.io/book-your-demo) to learn more or check out the [self-hosted deployment guide](./self-hosted.md).
TenantsTenants in ZenML Protenants.md
OrganizationsOrganizations in ZenML Proorganization.md
TeamsTeams in ZenML Proteams.md
RolesRoles in ZenML Proroles.md
Self-Hosted DeploymentsSelf-hosted ZenML Pro deploymentsself-hosted.md
ZenML Scarf
================ File: docs/book/getting-started/zenml-pro/roles.md ================ --- description: > Learn about the different roles and permissions you can assign to your team members in ZenML Pro. --- # ZenML Pro: Roles and Permissions ZenML Pro offers a robust role-based access control (RBAC) system to manage permissions across your organization and tenants. This guide will help you understand the different roles available, how to assign them, and how to create custom roles tailored to your team's needs. Please note that roles can be assigned to both individual users and [teams](./teams.md). ## Organization-Level Roles At the organization level, ZenML Pro provides three predefined roles: 1. **Org Admin** - Full control over the organization - Can add members, create and update tenants - Can manage billing information - Can assign roles to other members 2. **Org Editor** - Can manage tenants and teams - Cannot access subscription information - Cannot delete the organization 3. **Org Viewer** - Can view tenants within the organization - Read-only permissions ![Organization Roles](../../.gitbook/assets/org_members.png) To assign organization roles: 1. Navigate to the Organization settings page 2. Click on the "Members" tab. Here you can update roles for existing members. 3. Use the "Add members" button to add new members ![Screenshot showing the invite modal](../../.gitbook/assets/add_org_members.png) Some points to note: - In addition to adding organization roles, you might also want to add tenant roles for people who you want to have access to a specific tenant. - An organization admin can add themselves to a tenant with any tenant role they desire. - However, an organization editor and viewer cannot add themselves to existing tenants that they are not a part of. They won't be able to view such tenants in the organization either. - Currently, you cannot create custom organization roles via the ZenML Pro dashboard. However, this is possible via the [ZenML Pro API](https://cloudapi.zenml.io/). ## Tenant-Level Roles Tenant roles determine a user's permissions within a specific ZenML tenant. There are predefined roles available, and you can also create custom roles for more granular control. ![Image showing the tenant roles](../../.gitbook/assets/role_page.png) ### Predefined Tenant Roles 1. **Admin** - Full control over the tenant - Can create, read, update, and delete all resources ![Image showing the admin role](../../.gitbook/assets/admin_role.png) 2. **Editor** - Can create, read, and share resources - Cannot modify or delete existing resources 3. **Viewer** - Read-only access to all resources and information ### Custom Roles Custom roles allow you to define specific permissions for users or groups. To create a custom role for a tenant: 1. Go to the tenant settings page ![Image showing the tenant settings page](../../.gitbook/assets/custom_role_settings_page.png) 2. Click on "Roles" in the left sidebar and Select "Add Custom Role" ![Image showing the add custom role page](../../.gitbook/assets/tenant_roles_page.png) 3. Provide a name and description for the role. Choose a base role from which to inherit permissions ![Image showing the add custom role page](../../.gitbook/assets/create_role_modal.png) 4. Edit permissions as needed ![Image showing the add custom role page](../../.gitbook/assets/assign_permissions.png) A custom role allows you to set permissions for various resources, including: - Artifacts - Models - Model Versions - Pipelines - Runs - Stacks - Components - Secrets - Service Connectors For each resource, you can define the following permissions: - Create - Read - Update - Delete - Share You can then assign this role to a user or a team on the "Members" page. #### Managing permissions for roles To manage permissions for a role: 1. Go to the Roles page in tenant settings 2. Select the role you want to modify 3. Click on "Edit Permissions" 4. Adjust permissions for each resource type as needed ![Assign Permissions](../../.gitbook/assets/assign_permissions.png) ## Sharing individual resources While roles define permission on broad resource groups, users can also share individual resources through the dashboard like this: ![Share dialog](../../.gitbook/assets/share_dialog.png) ## Best Practices 1. **Least Privilege**: Assign the minimum necessary permissions to each role. 2. **Regular Audits**: Periodically review and update role assignments and permissions. 3. **Use Custom Roles**: Create custom roles for teams or projects with specific needs. 4. **Document Roles**: Maintain documentation of your custom roles and their intended use. By leveraging ZenML Pro's role-based access control, you can ensure that your team members have the right level of access to resources, maintaining security while enabling collaboration across your MLOps projects.
ZenML Scarf
================ File: docs/book/getting-started/zenml-pro/teams.md ================ --- description: > Learn about Teams in ZenML Pro and how they can be used to manage groups of users across your organization and tenants. --- # Organize users in Teams ZenML Pro introduces the concept of Teams to help you manage groups of users efficiently. A team is a collection of users that acts as a single entity within your organization and tenants. This guide will help you understand how teams work, how to create and manage them, and how to use them effectively in your MLOps workflows. ## Understanding Teams Teams in ZenML Pro offer several key benefits: 1. **Group Management**: Easily manage permissions for multiple users at once. 2. **Organizational Structure**: Reflect your company's structure or project teams in ZenML. 3. **Simplified Access Control**: Assign roles to entire teams rather than individual users. ## Creating and Managing Teams Teams are created at the organization level and can be assigned roles within tenants, similar to individual users. To create a team: 1. Navigate to the Organization settings page 2. Click on the "Teams" tab 3. Use the "Add team" button to add a new team ![Create Team](../../.gitbook/assets/create_team.png) When creating a team, you'll need to provide: - Team name - Description (optional) - Initial team members ## Adding Users to Teams To add users to an existing team: 1. Go to the "Teams" tab in Organization settings 2. Select the team you want to modify 3. Click on "Add Members" 4. Choose users from your organization to add to the team ![Add Team Members](../../.gitbook/assets/add_team_members.png) ## Assigning Teams to Tenants Teams can be assigned to tenants just like individual users. To add a team to a tenant: 1. Go to the tenant settings page 2. Click on "Members" tab and click on the "Teams" tab. 3. Select "Add Team" 4. Choose the team and assign a role ![Assign Team to Tenant](../../.gitbook/assets/assign_team_to_tenant.png) ## Team Roles and Permissions When you assign a role to a team within a tenant, all members of that team inherit the permissions associated with that role. This can be a predefined role (Admin, Editor, Viewer) or a custom role you've created. For example, if you assign the "Editor" role to a team in a specific tenant, all members of that team will have Editor permissions in that tenant. ![Team Roles](../../.gitbook/assets/team_roles.png) ## Best Practices for Using Teams 1. **Reflect Your Organization**: Create teams that mirror your company's structure or project groups. 3. **Combine with Custom Roles**: Use custom roles with teams for fine-grained access control. 4. **Regular Audits**: Periodically review team memberships and their assigned roles. 5. **Document Team Purposes**: Maintain clear documentation about each team's purpose and associated projects or tenants. By leveraging Teams in ZenML Pro, you can streamline user management, simplify access control, and better organize your MLOps workflows across your organization and tenants.
ZenML Scarf
================ File: docs/book/getting-started/zenml-pro/tenants.md ================ --- description: > Learn how to use tenants in ZenML Pro. --- # Tenants Tenants are individual, isolated deployments of the ZenML server. Each tenant has its own set of users, roles, and resources. Essentially, everything you do in ZenML Pro revolves around a tenant: all of your pipelines, stacks, runs, connectors and so on are scoped to a tenant. ![Image showing the tenant page](../../.gitbook/assets/custom_role_settings_page.png) The ZenML server that you get through a tenant is a supercharged version of the open-source ZenML server. This means that you get all the features of the open-source version, plus some extra Pro features. ## Create a Tenant in your organization A tenant is a crucial part of your Organization and holds all of your pipelines, experiments and models, among other things. You need to have a tenant to fully utilize the benefits that ZenML Pro brings. The following is how you can create a tenant yourself: - Go to your organization page - Click on the "+ New Tenant" button ![Image showing the create tenant page](../../.gitbook/assets/new_tenant.png) - Give your tenant a name and click on the "Create Tenant" button ![Image showing the create tenant modal](../../.gitbook/assets/new_tenant_modal.png) The tenant will then be created and added to your organization. In the meantime, you can already get started with setting up your environment for the onboarding experience. The image below shows you how the overview page looks like when you are being onboarded. Follow the instructions on the screen to get started. ![Image showing the onboarding experience](../../.gitbook/assets/tenant_onboarding.png) {% hint style="info" %} You can also create a tenant through the Cloud API by navigating to https://cloudapi.zenml.io/ and using the `POST /organizations` endpoint to create a tenant. {% endhint %} ## Organizing your tenants Organizing your tenants effectively is crucial for managing your MLOps infrastructure efficiently. There are primarily two dimensions to consider when structuring your tenants: ### Organizing tenants in `staging` and `production` One common approach is to separate your tenants based on the development stage of your ML projects. This typically involves creating at least two types of tenants: 1. **Staging Tenants**: These are used for development, testing, and experimentation. They provide a safe environment where data scientists and ML engineers can: - Develop and test new pipelines - Experiment with different models and hyperparameters - Validate changes before moving to production 2. **Production Tenants**: These host your live, customer-facing ML services. They are characterized by: - Stricter access controls - More rigorous monitoring and alerting - Optimized for performance and reliability This separation allows for a clear distinction between experimental work and production-ready systems, reducing the risk of untested changes affecting live services. ![Staging vs production tenants](../../.gitbook/assets/staging-production-tenants.png) ### Organizing tenants by business logic Another approach is to create tenants based on your organization's structure or specific use cases. This method can help in: 1. **Project-based Separation**: Create tenants for different ML projects or products. For example: - Recommendation System Tenant - Natural Language Processing Tenant - Computer Vision Tenant 2. **Team-based Separation**: Align tenants with your organizational structure: - Data Science Team Tenant - ML Engineering Team Tenant - Business Intelligence Team Tenant 3. **Data Sensitivity Levels**: Separate tenants based on data classification: - Public Data Tenant - Internal Data Tenant - Highly Confidential Data Tenant This organization method offers several benefits: - Improved resource allocation and cost tracking - Better alignment with team structures and workflows - Enhanced data security and compliance management ![Business logic-based tenant organization](../../.gitbook/assets/business-logic-tenants.png) Of course, both approaches of organizing your tenants can be mixed and matched to create a structure that works best for you. ### Best Practices for Tenant Organization Regardless of the approach you choose, consider these best practices: 1. **Clear Naming Conventions**: Use consistent, descriptive names for your tenants to easily identify their purpose. 2. **Access Control**: Implement [role-based access control](./roles.md) within each tenant to manage permissions effectively. 3. **Documentation**: Maintain clear documentation about the purpose and contents of each tenant. 4. **Regular Reviews**: Periodically review your tenant structure to ensure it still aligns with your organization's needs. 5. **Scalability**: Design your tenant structure to accommodate future growth and new projects. By thoughtfully organizing your tenants, you can create a more manageable, secure, and efficient MLOps environment that scales with your organization's needs. ## Using your tenant As previously mentioned, a tenant is a supercharged ZenML server that you can use to run your pipelines, carry out experiments and perform all the other actions you expect out of your ZenML server. Some Pro-only features that you can leverage in your tenant are as follows: - [Model Control Plane](../../../../docs/book/how-to/model-management-metrics/model-control-plane/register-a-model.md) - [Artifact Control Plane](../../how-to/data-artifact-management/handle-data-artifacts/README.md) - [Ability to run pipelines from the Dashboard](../../../../docs/book/how-to/trigger-pipelines/use-templates-rest-api.md), - [Create templates out of your pipeline runs](../../../../docs/book/how-to/trigger-pipelines/use-templates-rest-api.md) and [more](https://zenml.io/pro)! ### Accessing tenant docs Every tenant has a connection URL that you can use to connect your `zenml` client to your deployed Pro server. This URL can also be used to access the OpenAPI specification for the ZenML Server. Simply visit `/docs` on your browser to see a full list of methods that you can execute from it, like running a pipeline through the REST API. ![Image showing the tenant swagger docs](../../.gitbook/assets/swagger_docs_zenml.png) Read more about to access the API [here](../../reference/api-reference.md).
ZenML Scarf
================ File: docs/book/getting-started/core-concepts.md ================ --- icon: lightbulb description: Discovering the core concepts behind ZenML. --- # Core concepts ![A diagram of core concepts of ZenML OSS](../.gitbook/assets/core_concepts_oss.png) **ZenML** is an extensible, open-source MLOps framework for creating portable, production-ready **MLOps pipelines**. It's built for data scientists, ML Engineers, and MLOps Developers to collaborate as they develop to production. In order to achieve this goal, ZenML introduces various concepts for different aspects of an ML workflow and we can categorize these concepts under three different threads:
1. DevelopmentAs a developer, how do I design my machine learning workflows?1. Development
2. ExecutionWhile executing, how do my workflows utilize the large landscape of MLOps tooling/infrastructure?2. Execution
3. ManagementHow do I establish and maintain a production-grade and efficient solution?3. Management
{% embed url="https://www.youtube.com/embed/iCB4KNjl5vs" %} If you prefer visual learning, this short video demonstrates the key concepts covered below. {% endembed %} ## 1. Development First, let's look at the main concepts which play a role during the development stage of an ML workflow with ZenML. #### Step Steps are functions annotated with the `@step` decorator. The easiest one could look like this. ```python @step def step_1() -> str: """Returns a string.""" return "world" ``` These functions can also have inputs and outputs. For ZenML to work properly, these should preferably be typed. ```python @step(enable_cache=False) def step_2(input_one: str, input_two: str) -> str: """Combines the two strings passed in.""" combined_str = f"{input_one} {input_two}" return combined_str ``` #### Pipelines At its core, ZenML follows a pipeline-based workflow for your projects. A **pipeline** consists of a series of **steps**, organized in any order that makes sense for your use case. ![Representation of a pipeline dag.](../.gitbook/assets/01\_pipeline.png) As seen in the image, a step might use the outputs from a previous step and thus must wait until the previous step is completed before starting. This is something you can keep in mind when organizing your steps. Pipelines and steps are defined in code using Python _decorators_ or _classes_. This is where the core business logic and value of your work lives, and you will spend most of your time defining these two things. Even though pipelines are simple Python functions, you are only allowed to call steps within this function. The inputs for steps called within a pipeline can either be the outputs of previous steps or alternatively, you can pass in values directly (as long as they're JSON-serializable). ```python @pipeline def my_pipeline(): output_step_one = step_1() step_2(input_one="hello", input_two=output_step_one) ``` Executing the Pipeline is as easy as calling the function that you decorated with the `@pipeline` decorator. ```python if __name__ == "__main__": my_pipeline() ``` #### Artifacts Artifacts represent the data that goes through your steps as inputs and outputs and they are automatically tracked and stored by ZenML in the artifact store. They are produced by and circulated among steps whenever your step returns an object or a value. This means the data is not passed between steps in memory. Rather, when the execution of a step is completed they are written to storage, and when a new step gets executed they are loaded from storage. The serialization and deserialization logic of artifacts is defined by [Materializers](../how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md). #### Models Models are used to represent the outputs of a training process along with all metadata associated with that output. In other words: models in ZenML are more broadly defined as the weights as well as any associated information. Models are first-class citizens in ZenML and as such viewing and using them is unified and centralized in the ZenML API, client as well as on the [ZenML Pro](https://zenml.io/pro) dashboard. #### Materializers Materializers define how artifacts live in between steps. More precisely, they define how data of a particular type can be serialized/deserialized, so that the steps are able to load the input data and store the output data. All materializers use the base abstraction called the `BaseMaterializer` class. While ZenML comes built-in with various implementations of materializers for different datatypes, if you are using a library or a tool that doesn't work with our built-in options, you can write [your own custom materializer](../how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md) to ensure that your data can be passed from step to step. #### Parameters & Settings When we think about steps as functions, we know they receive input in the form of artifacts. We also know that they produce output (in the form of artifacts, stored in the artifact store). But steps also take parameters. The parameters that you pass into the steps are also (helpfully!) stored by ZenML. This helps freeze the iterations of your experimentation workflow in time, so you can return to them exactly as you run them. On top of the parameters that you provide for your steps, you can also use different `Setting`s to configure runtime configurations for your infrastructure and pipelines. #### Model and model versions ZenML exposes the concept of a `Model`, which consists of multiple different model versions. A model version represents a unified view of the ML models that are created, tracked, and managed as part of a ZenML project. Model versions link all other entities to a centralized view. ## 2. Execution Once you have implemented your workflow by using the concepts described above, you can focus your attention on the execution of the pipeline run. #### Stacks & Components When you want to execute a pipeline run with ZenML, **Stacks** come into play. A **Stack** is a collection of **stack components**, where each component represents the respective configuration regarding a particular function in your MLOps pipeline such as orchestration systems, artifact repositories, and model deployment platforms. For instance, if you take a close look at the default local stack of ZenML, you will see two components that are **required** in every stack in ZenML, namely an _orchestrator_ and an _artifact store_. ![ZenML running code on the Local Stack.](../.gitbook/assets/02\_pipeline\_local\_stack.png) {% hint style="info" %} Keep in mind, that each one of these components is built on top of base abstractions and is completely extensible. {% endhint %} #### Orchestrator An **Orchestrator** is a workhorse that coordinates all the steps to run in a pipeline. Since pipelines can be set up with complex combinations of steps with various asynchronous dependencies between them, the orchestrator acts as the component that decides what steps to run and when to run them. ZenML comes with a default _local orchestrator_ designed to run on your local machine. This is useful, especially during the exploration phase of your project. You don't have to rent a cloud instance just to try out basic things. #### Artifact Store An **Artifact Store** is a component that houses all data that pass through the pipeline as inputs and outputs. Each artifact that gets stored in the artifact store is tracked and versioned and this allows for extremely useful features like data caching which speeds up your workflows. Similar to the orchestrator, ZenML comes with a default _local artifact store_ designed to run on your local machine. This is useful, especially during the exploration phase of your project. You don't have to set up a cloud storage system to try out basic things. #### Flavor ZenML provides a dedicated base abstraction for each stack component type. These abstractions are used to develop solutions, called **Flavors**, tailored to specific use cases/tools. With ZenML installed, you get access to a variety of built-in and integrated Flavors for each component type, but users can also leverage the base abstractions to create their own custom flavors. #### Stack Switching When it comes to production-grade solutions, it is rarely enough to just run your workflow locally without including any cloud infrastructure. Thanks to the separation between the pipeline code and the stack in ZenML, you can easily switch your stack independently from your code. For instance, all it would take you to switch from an experimental local stack running on your machine to a remote stack that employs a full-fledged cloud infrastructure is a single CLI command. ## 3. Management In order to benefit from the aforementioned core concepts to their fullest extent, it is essential to deploy and manage a production-grade environment that interacts with your ZenML installation. #### ZenML Server To use _stack components_ that are running remotely on a cloud infrastructure, you need to deploy a [**ZenML Server**](../user-guide/production-guide/deploying-zenml.md) so it can communicate with these stack components and run your pipelines. The server is also responsible for managing ZenML business entities like pipelines, steps, models, etc. ![Visualization of the relationship between code and infrastructure.](../.gitbook/assets/04\_architecture.png) #### Server Deployment In order to benefit from the advantages of using a deployed ZenML server, you can either choose to use the [**ZenML Pro SaaS offering**](zenml-pro/README.md) which provides a control plane for you to create managed instances of ZenML servers, or [deploy it in your self-hosted environment](deploying-zenml/README.md). #### Metadata Tracking On top of the communication with the stack components, the **ZenML Server** also keeps track of all the bits of metadata around a pipeline run. With a ZenML server, you are able to access all of your previous experiments with the associated details. This is extremely helpful in troubleshooting. #### Secrets The **ZenML Server** also acts as a [centralized secrets store](deploying-zenml/secret-management.md) that safely and securely stores sensitive data such as credentials used to access the services that are part of your stack. It can be configured to use a variety of different backends for this purpose, such as the AWS Secrets Manager, GCP Secret Manager, Azure Key Vault, and Hashicorp Vault. Secrets are sensitive data that you don't want to store in your code or configure alongside your stacks and pipelines. ZenML includes a [centralized secrets store](deploying-zenml/secret-management.md) that you can use to store and access your secrets securely. #### Collaboration Collaboration is a crucial aspect of any MLOps team as they often need to bring together individuals with diverse skills and expertise to create a cohesive and effective workflow for machine learning projects. A successful MLOps team requires seamless collaboration between data scientists, engineers, and DevOps professionals to develop, train, deploy, and maintain machine learning models. With a deployed **ZenML Server**, users have the ability to create their own teams and project structures. They can easily share pipelines, runs, stacks, and other resources, streamlining the workflow and promoting teamwork. #### Dashboard The **ZenML Dashboard** also communicates with **the ZenML Server** to visualize your _pipelines_, _stacks_, and _stack components_. The dashboard serves as a visual interface to showcase collaboration with ZenML. You can invite _users_, and share your stacks with them. When you start working with ZenML, you'll start with a local ZenML setup, and when you want to transition you will need to [deploy ZenML](deploying-zenml/README.md). Don't worry though, there is a one-click way to do it which we'll learn about later. #### VS Code Extension ZenML also provides a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=ZenML.zenml-vscode) that allows you to interact with your ZenML stacks, runs and server directly from your VS Code editor. If you're working on code in your editor, you can easily switch and inspect the stacks you're using, delete and inspect pipelines as well as even switch stacks.
ZenML Scarf
================ File: docs/book/getting-started/installation.md ================ --- icon: cauldron description: Installing ZenML and getting started. --- # Installation **ZenML** is a Python package that can be installed directly via `pip`: ```shell pip install zenml ``` {% hint style="warning" %} Note that ZenML currently supports **Python 3.9, 3.10, 3.11 and 3.12**. Please make sure that you are using a supported Python version. {% endhint %} ## Install with the dashboard ZenML comes bundled with a web dashboard that lives inside a [sister repository](https://github.com/zenml-io/zenml-dashboard). In order to get access to the dashboard **locally**, you need to launch the [ZenML Server and Dashboard locally](deploying-zenml/README.md). For this, you need to install the optional dependencies for the ZenML Server: ```shell pip install "zenml[server]" ``` {% hint style="info" %} We highly encourage you to install ZenML in a virtual environment. At ZenML, We like to use [virtualenvwrapper](https://virtualenvwrapper.readthedocs.io/en/latest/) or [pyenv-virtualenv](https://github.com/pyenv/pyenv-virtualenv) to manage our Python virtual environments. {% endhint %} ## Installing onto MacOS with Apple Silicon (M1, M2) A change in how forking works on Macs running on Apple Silicon means that you should set the following environment variable which will ensure that your connections to the server remain unbroken: ```bash export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES ``` You can read more about this [here](http://sealiesoftware.com/blog/archive/2017/6/5/Objective-C_and_fork_in_macOS_1013.html). This environment variable is needed if you are working with a local server on your Mac, but if you're just using ZenML as a client / CLI and connecting to a deployed server then you don't need to set it. ## Nightly builds ZenML also publishes nightly builds under the [`zenml-nightly` package name](https://pypi.org/project/zenml-nightly/). These are built from the latest [`develop` branch](https://github.com/zenml-io/zenml/tree/develop) (to which work ready for release is published) and are not guaranteed to be stable. To install the nightly build, run: ```shell pip install zenml-nightly ``` ## Verifying installations Once the installation is completed, you can check whether the installation was successful either through Bash: ```bash zenml version ``` or through Python: ```python import zenml print(zenml.__version__) ``` If you would like to learn more about the current release, please visit our [PyPi package page.](https://pypi.org/project/zenml) ## Running with Docker `zenml` is also available as a Docker image hosted publicly on [DockerHub](https://hub.docker.com/r/zenmldocker/zenml). Use the following command to get started in a bash environment with `zenml` available: ```shell docker run -it zenmldocker/zenml /bin/bash ``` If you would like to run the ZenML server with Docker: ```shell docker run -it -d -p 8080:8080 zenmldocker/zenml-server ```
ZenML Scarf
## Deploying the server Though ZenML can run entirely as a pip package on a local system, complete with the dashboard. You can do this easily: ```shell pip install "zenml[server]" zenml login --local # opens the dashboard locally ``` However, advanced ZenML features are dependent on a centrally-deployed ZenML server accessible to other MLOps stack components. You can read more about it [here](deploying-zenml/README.md). For the deployment of ZenML, you have the option to either [self-host](deploying-zenml/README.md) it or register for a free [ZenML Pro](https://cloud.zenml.io/signup?utm\_source=docs\&utm\_medium=referral\_link\&utm\_campaign=cloud\_promotion\&utm\_content=signup\_link) account. ================ File: docs/book/getting-started/system-architectures.md ================ --- icon: building-columns description: Different variations of the ZenML architecture depending on your needs. --- # System Architecture This guide walks through the various ways that ZenML can be deployed, from self-hosted OSS, to SaaS, to self-hosted ZenML Pro! ## ZenML OSS (Self-hosted) {% hint style="info" %} This page is intended as a high level overview. To learn more about how about to deploy ZenML OSS, read [this guide](../getting-started/deploying-zenml/README.md). {% endhint %} A ZenML OSS deployment consists of the following moving pieces: * **ZenML OSS Server**: This is a FastAPI app that manages metadata of pipelines, artifacts, stacks etc. Note: In ZenML Pro, the notion of a ZenML server is replaced with what is known as a "Tenant". For all intents and purposes, consider a ZenML Tenant to be a ZenML OSS server that comes with more functionality. * **OSS Metadata Store**: This is where all ZenML tenant metadata is stored, including ML metadata such as tracking and versioning information about pipelines and models. * **OSS Dashboard**: This is a ReactJS app that shows pipelines, runs, etc. * **Secrets Store**: All secrets and credentials required to access customer infrastructure services are stored in a secure secrets store. The ZenML Pro API has access to these secrets and uses them to access customer infrastructure services on behalf of the ZenML Pro. The secrets store can be hosted either by the ZenML Pro or by the customer. ![ZenML OSS server deployment architecture](../.gitbook/assets/oss_simple_deployment.png) ZenML OSS is free with Apache 2.0 license. Learn how to deploy it [here](./deploying-zenml/README.md). {% hint style="info" %} To learn more about the core concepts for ZenML OSS, go [here](../getting-started/core-concepts.md). {% endhint %} ## ZenML Pro (SaaS or Self-hosted) {% hint style="info" %} If you're interested in assessing ZenML Pro SaaS, you can create a [free account](https://cloud.zenml.io/?utm\_source=docs\&utm\_medium=referral\_link\&utm\_campaign=cloud\_promotion\&utm\_content=signup\_link). If would like to self-host ZenML Pro, please [book a demo](https://zenml.io/book-a-demo). {% endhint %} The above deployment can be augmented with the ZenML Pro components: * **ZenML Pro Control Plane**: This is the central controlling entity of all tenants. * **Pro Dashboard**: This is a dashboard that builds on top of the OSS dashboard, and add further functionality. * **Pro Metadata Store**: This is a PostgreSQL database where all ZenML Pro related metadata is stored such as roles, permissions, teams, and tenant management related data. * **Pro Add-ons**: These are Python modules injected into the OSS Server for enhanced functionality. * **Identity Provider**: ZenML Pro offers flexible authentication options. In cloud-hosted deployments, it integrates with [Auth0](https://auth0.com/), allowing users to log in via social media or corporate credentials. For self-hosted deployments, customers can configure their own identity management solution, with ZenML Pro supporting custom OIDC provider integration. This allows organizations to leverage their existing identity infrastructure for authentication and authorization, whether using the cloud service or deploying on-premises. ![ZenML Pro deployment architecture](../.gitbook/assets/pro_deployment_simple.png) ZenML Pro offers many additional features to increase your teams productivity. No matter your specific needs, the hosting options for ZenML Pro range from easy SaaS integration to completely air-gapped deployments on your own infrastructure. You might have noticed this architecture builds on top of the ZenML OSS system architecture. Therefore, if you already have ZenML OSS deployed, it is easy to enroll it as part of a ZenML Pro deployment! The above components interact with other MLOps stack components, secrets, and data in the following scenarios described below. {% hint style="info" %} To learn more about the core concepts for ZenML Pro, go [here](../getting-started/zenml-pro/core-concepts.md) {% endhint %} ### ZenML Pro SaaS Architecture ![ZenML Pro SaaS deployment with ZenML secret store](../.gitbook/assets/cloud_architecture_scenario_1.png) For the ZenML Pro SaaS deployment case, all ZenML services are hosted on infrastructure hosted by the ZenML Team. Customer secrets and credentials required to access customer infrastructure are stored and managed by the ZenML Pro Control Plane. On the ZenML Pro infrastructure, only ML _metadata_ (e.g. pipeline and model tracking and versioning information) is stored. All the actual ML data artifacts (e.g. data produced or consumed by pipeline steps, logs and visualizations, models) are stored on the customer cloud. This can be set up quite easily by configuring an [artifact store](../component-guide/artifact-stores/artifact-stores.md) with your MLOps stack. Your tenant only needs permissions to read from this data to display artifacts on the ZenML dashboard. The tenant also needs direct access to parts of the customer infrastructure services to support dashboard control plane features such as CI/CD, triggering and running pipelines, triggering model deployments and so on. The advantage of this setup is that it is a fully-managed service, and is very easy to get started with. However, for some clients even some metadata can be sensitive; these clients should refer to the other architecture diagram.
Detailed Architecture Diagram for SaaS deployment
ZenML Pro Full SaaS deployment
ZenML Pro Full SaaS deployment with ZenML secret store
We also offer a hybrid SaaS option where customer secrets are stored on the customer side. In this case, the customer connects their own secret store directly to the ZenML server that is managed by us. All ZenML secrets used by running pipelines to access infrastructure services and resources are stored in the customer secret store. This allows users to use [service connectors](../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) and the [secrets API](../how-to/project-setup-and-management/interact-with-secrets.md) to authenticate ZenML pipelines and the ZenML Pro to third-party services and infrastructure while ensuring that credentials are always stored on the customer side. {% endhint %} ![ZenML Pro SaaS deployment with Customer secret store](../.gitbook/assets/cloud_architecture_scenario_1_1.png)
Detailed Architecture Diagram for SaaS deployment with custom secret store configuration
ZenML Pro Full SaaS deployment with custom secret store
ZenML Pro Full SaaS deployment with customer secret store
### ZenML Pro Self-Hosted Architecture ![ZenML Pro self-hosted deployment](../.gitbook/assets/cloud_architecture_scenario_2.png) In the case of self-hosting ZenML Pro, all services, data, and secrets are deployed on the customer cloud. This is meant for customers who require completely air-gapped deployments, for the tightest security standards. [Reach out to us](mailto:cloud@zenml.io) if you want to set this up.
Detailed Architecture Diagram for self-hosted ZenML Pro deployment
ZenML Pro self-hosted deployment details
ZenML Pro self-hosted deployment details
Are you interested in ZenML Pro? [Sign up](https://cloud.zenml.io/?utm\_source=docs\&utm\_medium=referral\_link\&utm\_campaign=cloud\_promotion\&utm\_content=signup\_link) and get access to Scenario 1. with a free 14-day trial now!
ZenML Scarf
================ File: docs/book/how-to/advanced-topics/README.md ================ --- icon: user-ninja --- # Advanced Topics This section covers advanced features and configurations in ZenML. ================ File: docs/book/how-to/configuring-zenml/configuring-zenml.md ================ --- description: Configuring ZenML's default behavior --- # Configuring ZenML There are various ways to adapt how ZenML behaves in certain situations. This guide walks users through how to configure certain aspects of ZenML.
ZenML Scarf
================ File: docs/book/how-to/contribute-to-zenml/implement-a-custom-integration.md ================ --- description: Creating an external integration and contributing to ZenML --- # Implement a custom integration ![ZenML integrates with a number of tools from the MLOps landscape](../../../.gitbook/assets/sam-side-by-side-full-text.png) One of the main goals of ZenML is to find some semblance of order in the ever-growing MLOps landscape. ZenML already provides [numerous integrations](https://zenml.io/integrations) into many popular tools, and allows you to come up with ways to [implement your own stack component flavors](../infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md) in order to fill in any gaps that are remaining. _However, what if you want to make your extension of ZenML part of the main codebase, to share it with others?_ If you are such a person, e.g., a tooling provider in the ML/MLOps space, or just want to contribute a tooling integration to ZenML, this guide is intended for you. ### Step 1: Plan out your integration In [the previous page](../infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md), we looked at the categories and abstractions that core ZenML defines. In order to create a new integration into ZenML, you would need to first find the categories that your integration belongs to. The list of categories can be found [here](../../component-guide/README.md) as well. Note that one integration may belong to different categories: For example, the cloud integrations (AWS/GCP/Azure) contain [container registries](../../component-guide/container-registries/container-registries.md), [artifact stores](../../component-guide/artifact-stores/artifact-stores.md) etc. ### Step 2: Create individual stack component flavors Each category selected above would correspond to a [stack component type](../../component-guide/README.md). You can now start developing individual stack component flavors for this type by following the detailed instructions on the respective pages. Before you package your new components into an integration, you may want to use/test them as a regular custom flavor. For instance, if you are [developing a custom orchestrator](../../component-guide/orchestrators/custom.md) and your flavor class `MyOrchestratorFlavor` is defined in `flavors/my_flavor.py`, you can register it by using: ```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](../project-setup-and-management/setting-up-a-project-repository/README.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 ``` See the docs on extensibility of the different components [here](../../component-guide/README.md) or get inspired by the many integrations that are already implemented such as [the MLflow experiment tracker](../../component-guide/experiment-trackers/mlflow.md). ### Step 3: Create an integration class Once you are finished with your flavor implementations, you can start the process of packaging them into your integration and ultimately the base ZenML package. Follow this checklist to prepare everything: **1. Clone Repo** Once your stack components work as a custom flavor, you can now [clone the main zenml repository](https://github.com/zenml-io/zenml) and follow the [contributing guide](https://github.com/zenml-io/zenml/blob/main/CONTRIBUTING.md) to set up your local environment for develop. **2. Create the integration directory** All integrations live within [`src/zenml/integrations/`](https://github.com/zenml-io/zenml/tree/main/src/zenml/integrations) in their own sub-folder. You should create a new folder in this directory with the name of your integration. An example integration directory would be structured as follows: ``` /src/zenml/integrations/ <- ZenML integration directory <- Root integration directory | ├── artifact-stores <- Separated directory for | ├── __init_.py every type | └── <- Implementation class for the | artifact store flavor ├── flavors | ├── __init_.py | └── <- Config class and flavor | └── __init_.py <- Integration class ``` **3. Define the name of your integration in constants** In [`zenml/integrations/constants.py`](https://github.com/zenml-io/zenml/blob/main/src/zenml/integrations/constants.py), add: ```python EXAMPLE_INTEGRATION = "" ``` This will be the name of the integration when you run: ```shell zenml integration install ``` **4. Create the integration class \_\_init\_\_.py** In `src/zenml/integrations//init__.py` you must now create a new class, which is a subclass of the `Integration` class, set some important attributes (`NAME` and `REQUIREMENTS`), and overwrite the `flavors` class method. ```python from zenml.integrations.constants import from zenml.integrations.integration import Integration from zenml.stack import Flavor # This is the flavor that will be used when registering this stack component # `zenml register ... -f example-orchestrator-flavor` EXAMPLE_ORCHESTRATOR_FLAVOR = <"example-orchestrator-flavor"> # Create a Subclass of the Integration Class class ExampleIntegration(Integration): """Definition of Example Integration for ZenML.""" NAME = REQUIREMENTS = [""] @classmethod def flavors(cls) -> List[Type[Flavor]]: """Declare the stack component flavors for the integration.""" from zenml.integrations. import return [] ExampleIntegration.check_installation() # this checks if the requirements are installed ``` Have a look at the [MLflow Integration](https://github.com/zenml-io/zenml/blob/main/src/zenml/integrations/mlflow/\_\_init\_\_.py) as an example for how it is done. **5. Import in all the right places** The Integration itself must be imported within [`src/zenml/integrations/__init__.py`](https://github.com/zenml-io/zenml/blob/main/src/zenml/integrations/\_\_init\_\_.py). ### Step 4: Create a PR and celebrate :tada: You can now [create a PR](https://github.com/zenml-io/zenml/compare) to ZenML and wait for the core maintainers to take a look. Thank you so much for your contribution to the codebase, rock on! 💜
ZenML Scarf
================ File: docs/book/how-to/contribute-to-zenml/README.md ================ --- icon: handshake-simple description: Contributing to ZenML. --- # Contribute to ZenML Thank you for considering contributing to ZenML! ## How to contribute We are very happy about any contributions to ZenML, whether it is a new feature, an improvement to the documentation, a new integration, or a bug report. This docs section contains guides on how to contribute features like new custom integrations to ZenML. In general, you should refer to the [ZenML contribution guide](https://github.com/zenml-io/zenml/blob/main/CONTRIBUTING.md) for more details on the best practices and the conventions we follow at ZenML.
ZenML Scarf
================ File: docs/book/how-to/control-logging/disable-colorful-logging.md ================ --- description: How to disable colorful logging in ZenML. --- # Disable colorful logging By default, ZenML uses colorful logging to make it easier to read logs. However, if you wish to disable this feature, you can do so by setting the following environment variable: ```bash ZENML_LOGGING_COLORS_DISABLED=true ``` Note that setting this on the [client environment](../pipeline-development/configure-python-environments/README.md#client-environment-or-the-runner-environment) (e.g. your local machine which runs the pipeline) will automatically disable colorful logging on remote pipeline runs. If you wish to only disable it locally, but turn on for remote pipeline runs, you can set the `ZENML_LOGGING_COLORS_DISABLED` environment variable in your pipeline runs environment as follows: ```python docker_settings = DockerSettings(environment={"ZENML_LOGGING_COLORS_DISABLED": "false"}) # Either add it to the decorator @pipeline(settings={"docker": docker_settings}) def my_pipeline() -> None: my_step() # Or configure the pipelines options my_pipeline = my_pipeline.with_options( settings={"docker": docker_settings} ) ```
ZenML Scarf
================ File: docs/book/how-to/control-logging/disable-rich-traceback.md ================ --- description: How to disable rich traceback output in ZenML. --- # Disable `rich` traceback output By default, ZenML uses the [`rich`](https://rich.readthedocs.io/en/stable/traceback.html) library to display rich traceback output. This is especially useful when debugging your pipelines. However, if you wish to disable this feature, you can do so by setting the following environment variable: ```bash export ZENML_ENABLE_RICH_TRACEBACK=false ``` This will ensure that you see only the plain text traceback output. Note that setting this on the [client environment](../pipeline-development/configure-python-environments/README.md#client-environment-or-the-runner-environment) (e.g. your local machine which runs the pipeline) will **not automatically disable rich tracebacks on remote pipeline runs**. That means setting this variable locally with only effect pipelines that run locally. If you wish to disable it also for [remote pipeline runs](../../user-guide/production-guide/cloud-orchestration.md), you can set the `ZENML_ENABLE_RICH_TRACEBACK` environment variable in your pipeline runs environment as follows: ```python docker_settings = DockerSettings(environment={"ZENML_ENABLE_RICH_TRACEBACK": "false"}) # Either add it to the decorator @pipeline(settings={"docker": docker_settings}) def my_pipeline() -> None: my_step() # Or configure the pipelines options my_pipeline = my_pipeline.with_options( settings={"docker": docker_settings} ) ```
ZenML Scarf
================ File: docs/book/how-to/control-logging/enable-or-disable-logs-storing.md ================ # Enable or disable logs storing By default, ZenML uses a logging handler to capture the logs that occur during the execution of a step. Users are free to use the default python logging module or print statements, and ZenML's logging handler will catch these logs and store them. ```python import logging from zenml import step @step def my_step() -> None: logging.warning("`Hello`") # You can use the regular `logging` module. print("World.") # You can utilize `print` statements as well. ``` These logs are stored within the respective artifact store of your stack. You can display the logs in the dashboard as follows: ![Displaying step logs on the dashboard](../../.gitbook/assets/zenml_step_logs.png) {% hint style="warning" %} Note that if you are not connected to a cloud artifact store with a service connector configured then you will not be able to view your logs in the dashboard. Read more [here](./view-logs-on-the-dasbhoard.md). {% endhint %} If you do not want to store the logs in your artifact store, you can: 1. Disable it by using the `enable_step_logs` parameter either with your `@pipeline` or `@step` decorator: ```python from zenml import pipeline, step @step(enable_step_logs=False) # disables logging for this step def my_step() -> None: ... @pipeline(enable_step_logs=False) # disables logging for the entire pipeline def my_pipeline(): ... ``` 2. Disable it by using the environmental variable `ZENML_DISABLE_STEP_LOGS_STORAGE` and setting it to `true`. This environmental variable takes precedence over the parameters mentioned above. Note this environmental variable needs to be set on the [execution environment](../pipeline-development/configure-python-environments/README.md#execution-environments), i.e., on the orchestrator level: ```python docker_settings = DockerSettings(environment={"ZENML_DISABLE_STEP_LOGS_STORAGE": "true"}) # Either add it to the decorator @pipeline(settings={"docker": docker_settings}) def my_pipeline() -> None: my_step() # Or configure the pipelines options my_pipeline = my_pipeline.with_options( settings={"docker": docker_settings} ) ```
ZenML Scarf
================ File: docs/book/how-to/control-logging/README.md ================ --- icon: memo-circle-info description: Configuring ZenML's default logging behavior --- # Control logging ZenML produces various kinds of logs: * The [ZenML Server](../../getting-started/deploying-zenml/README.md) produces server logs (like any FastAPI server). * The [Client or Runner](../pipeline-development/configure-python-environments/README.md#client-environment-or-the-runner-environment) environment produces logs, for example after running a pipeline. These are steps that are typically before, after, and during the creation of a pipeline run. * The [Execution environment](../pipeline-development/configure-python-environments/README.md#execution-environments) (on the orchestrator level) produces logs when it executes each step of a pipeline. These are logs that are typically written in your steps using the python `logging` module. This section talks about how users can control logging behavior in these various environments.
ZenML Scarf
================ File: docs/book/how-to/control-logging/set-logging-verbosity.md ================ --- description: How to set the logging verbosity in ZenML. --- # Set logging verbosity By default, ZenML sets the logging verbosity to `INFO`. If you wish to change this, you can do so by setting the following environment variable: ```bash export ZENML_LOGGING_VERBOSITY=INFO ``` Choose from `INFO`, `WARN`, `ERROR`, `CRITICAL`, `DEBUG`. This will set the logs to whichever level you suggest. Note that setting this on the [client environment](../pipeline-development/configure-python-environments/README.md#client-environment-or-the-runner-environment) (e.g. your local machine which runs the pipeline) will **not automatically set the same logging verbosity for remote pipeline runs**. That means setting this variable locally with only effect pipelines that run locally. If you wish to control for [remote pipeline runs](../../user-guide/production-guide/cloud-orchestration.md), you can set the `ZENML_LOGGING_VERBOSITY` environment variable in your pipeline runs environment as follows: ```python docker_settings = DockerSettings(environment={"ZENML_LOGGING_VERBOSITY": "DEBUG"}) # Either add it to the decorator @pipeline(settings={"docker": docker_settings}) def my_pipeline() -> None: my_step() # Or configure the pipelines options my_pipeline = my_pipeline.with_options( settings={"docker": docker_settings} ) ```
ZenML Scarf
================ File: docs/book/how-to/control-logging/view-logs-on-the-dasbhoard.md ================ # Viewing logs on the dashboard By default, ZenML uses a logging handler to capture the logs that occur during the execution of a step. Users are free to use the default python logging module or print statements, and ZenML's logging handler will catch these logs and store them. ```python import logging from zenml import step @step def my_step() -> None: logging.warning("`Hello`") # You can use the regular `logging` module. print("World.") # You can utilize `print` statements as well. ``` These logs are stored within the respective artifact store of your stack. This means that you can only view these logs in the dashboard *if the deployed ZenML server has direct access to the underlying artifact store*. There are two cases in which this will be true: * In case of a local ZenML server (via `zenml login --local`), both local and remote artifact stores may be accessible, depending on configuration of the client. * In case of a deployed ZenML server, logs for runs on a [local artifact store](../../component-guide/artifact-stores/local.md) will not be accessible. Logs for runs using a [remote artifact store](../../user-guide/production-guide/remote-storage.md) **may be** accessible, if the artifact store has been configured with a [service connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md). Please read [this chapter](../../user-guide/production-guide/remote-storage.md) of the production guide to learn how to configure a remote artifact store with a service connector. If configured correctly, the logs are displayed in the dashboard as follows: ![Displaying step logs on the dashboard](../../.gitbook/assets/zenml_step_logs.png) {% hint style="warning" %} If you do not want to store the logs for your pipeline (for example due to performance reduction or storage limits), you can follow [these instructions](./enable-or-disable-logs-storing.md). {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/customize-docker-builds/define-where-an-image-is-built.md ================ --- description: Defining the image builder. --- # 🐳 Define where an image is built ZenML executes pipeline steps sequentially in the active Python environment when running locally. However, with remote [orchestrators](../../component-guide/orchestrators/orchestrators.md) or [step operators](../../component-guide/step-operators/step-operators.md), ZenML builds [Docker](https://www.docker.com/) images to run your pipeline in an isolated, well-defined environment. By default, execution environments are created locally in the client environment using the local Docker client. However, this requires Docker installation and permissions. ZenML offers [image builders](../../component-guide/image-builders/image-builders.md), a special [stack component](../../component-guide/README.md), allowing users to build and push Docker images in a different specialized _image builder environment_. Note that even if you don't configure an image builder in your stack, ZenML still uses the [local image builder](../../component-guide/image-builders/local.md) to retain consistency across all builds. In this case, the image builder environment is the same as the [client environment](../pipeline-development/configure-python-environments/README.md#client-environment-or-the-runner-environment). 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/how-to/customize-docker-builds/docker-settings-on-a-pipeline.md ================ --- description: Using Docker images to run your pipeline. --- # Specify Docker settings for a pipeline When a [pipeline is run with a remote orchestrator](../pipeline-development/configure-python-environments/README.md) a [Dockerfile](https://docs.docker.com/engine/reference/builder/) is dynamically generated at runtime. It is then used to build the Docker image using the [image builder](../pipeline-development/configure-python-environments/README.md#image-builder-environment) component of your stack. The Dockerfile consists of the following steps: * **Starts from a parent image** that has **ZenML installed**. By default, this will use the [official ZenML image](https://hub.docker.com/r/zenmldocker/zenml/) for the Python and ZenML version that you're using in the active Python environment. If you want to use a different image as the base for the following steps, check out [this guide](./docker-settings-on-a-pipeline.md#using-a-custom-parent-image). * **Installs additional pip dependencies**. ZenML will automatically detect which integrations are used in your stack and install the required dependencies. If your pipeline needs any additional requirements, check out our [guide on including custom dependencies](specify-pip-dependencies-and-apt-packages.md). * **Optionally copies your source files**. Your source files need to be available inside the Docker container so ZenML can execute your step code. Check out [this section](./which-files-are-built-into-the-image.md) for more information on how you can customize how ZenML handles your source files in Docker images. * **Sets user-defined environment variables.** The process described above is automated by ZenML and covers the most basic use cases. This section covers various ways to customize the Docker build process to fit your needs. For a full list of configuration options, check out [the DockerSettings object on the SDKDocs](https://sdkdocs.zenml.io/latest/core_code_docs/core-config/#zenml.config.docker_settings.DockerSettings). ## How to configure settings for a pipeline Customizing the Docker builds for your pipelines and steps is done using the [DockerSettings](https://sdkdocs.zenml.io/latest/core_code_docs/core-config/#zenml.config.docker_settings.DockerSettings) class which you can import like this: ```python from zenml.config import DockerSettings ``` There are many ways in which you can supply these settings: * Configuring them on a pipeline applies the settings to all steps of that pipeline: ```python from zenml.config import DockerSettings docker_settings = DockerSettings() # Either add it to the decorator @pipeline(settings={"docker": docker_settings}) def my_pipeline() -> None: my_step() # Or configure the pipelines options my_pipeline = my_pipeline.with_options( settings={"docker": docker_settings} ) ``` * Configuring them on a step gives you more fine-grained control and enables you to build separate specialized Docker images for different steps of your pipelines: ```python docker_settings = DockerSettings() # Either add it to the decorator @step(settings={"docker": docker_settings}) def my_step() -> None: pass # Or configure the step options my_step = my_step.with_options( settings={"docker": docker_settings} ) ``` * Using a YAML configuration file as described [here](../pipeline-development/use-configuration-files/README.md): ```yaml settings: docker: ... steps: step_name: settings: docker: ... ``` Check out [this page](../pipeline-development/use-configuration-files/configuration-hierarchy.md) for more information on the hierarchy and precedence of the various ways in which you can supply the settings. ### Specifying Docker build options If you want to specify build options that get passed to the build method of the [image builder](../pipeline-development/configure-python-environments/README.md#image-builder-environment). For the default local image builder, these options get passed to the [`docker build` command](https://docker-py.readthedocs.io/en/stable/images.html#docker.models.images.ImageCollection.build). ```python docker_settings = DockerSettings(build_config={"build_options": {...}}) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` {% hint style="info" %} If you're running your pipelines on MacOS with ARM architecture, the local Docker caching does not work unless you specify the target platform of the image: ```python docker_settings = DockerSettings(build_config={"build_options": {"platform": "linux/amd64"}}) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` {% endhint %} ### Using a custom parent image By default, ZenML performs all the steps described above on top of the [official ZenML image](https://hub.docker.com/r/zenmldocker/zenml/) for the Python and ZenML version in the active Python environment. To have more control over the entire environment used to execute your pipelines, you can either specify a custom pre-built parent image or a Dockerfile that ZenML uses to build a parent image for you. {% hint style="info" %} If you're going to use a custom parent image (either pre-built or by specifying a Dockerfile), you need to make sure that it has Python, pip, and ZenML installed for it to work. If you need a starting point, you can take a look at the Dockerfile that ZenML uses [here](https://github.com/zenml-io/zenml/blob/main/docker/base.Dockerfile). {% endhint %} #### Using a pre-built parent image To use a static parent image (e.g., with internal dependencies installed) that doesn't need to be rebuilt on every pipeline run, specify it in the Docker settings for your pipeline: ```python docker_settings = DockerSettings(parent_image="my_registry.io/image_name:tag") @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` To use this image directly to run your steps without including any code or installing any requirements on top of it, skip the Docker builds by specifying it in the Docker settings: ```python docker_settings = DockerSettings( parent_image="my_registry.io/image_name:tag", skip_build=True ) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` {% hint style="warning" %} This is an advanced feature and may cause unintended behavior when running your pipelines. If you use this, ensure your code files are correctly included in the image you specified. Read in detail about this feature [here](./use-a-prebuilt-image.md) before proceeding. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/customize-docker-builds/docker-settings-on-a-step.md ================ --- description: You have the option to customize the Docker settings at a step level. --- # Docker settings on a step By default every step of a pipeline uses the same Docker image that is defined at the [pipeline level](./docker-settings-on-a-pipeline.md). Sometimes your steps will have special requirements that make it necessary to define a different Docker image for one or many steps. This can easily be accomplished by adding the [DockerSettings](https://sdkdocs.zenml.io/latest/core_code_docs/core-config/#zenml.config.docker_settings.DockerSettings) to the step decorator directly. ```python from zenml import step from zenml.config import DockerSettings @step( settings={ "docker": DockerSettings( parent_image="pytorch/pytorch:1.12.1-cuda11.3-cudnn8-runtime" ) } ) def training(...): ... ``` Alternatively, this can also be done within the configuration file. ```yaml steps: training: settings: docker: parent_image: pytorch/pytorch:2.2.0-cuda11.8-cudnn8-runtime required_integrations: - gcp - github requirements: - zenml # Make sure to include ZenML for other parent images - numpy ```
ZenML Scarf
================ File: docs/book/how-to/customize-docker-builds/how-to-reuse-builds.md ================ --- description: > Learn how to reuse builds to speed up your pipeline runs. --- # How to reuse builds When you run a pipeline, ZenML will check if a build with the same pipeline and stack exists. If it does, it will reuse that build. If it doesn't, ZenML will create a new build. This guide explains what a build is and the best practices around reusing builds. ## What is a build? A pipeline build is an encapsulation of a pipeline and the stack it was run on. It contains the Docker images that were built for the pipeline with all the requirements from the stack, integrations and the user. Optionally, it also contains the pipeline code. You can list all the builds for a pipeline using the CLI: ```bash zenml pipeline builds list --pipeline_id='startswith:ab53ca' ``` You can also create a build manually using the CLI: ```bash zenml pipeline build --stack vertex-stack my_module.my_pipeline_instance ``` You can use the options to specify the configuration file and the stack to use for the build. The source should be a path to a pipeline instance. Learn more about the build function [here](https://sdkdocs.zenml.io/latest/core_code_docs/core-new/#zenml.new.pipelines.pipeline.Pipeline.build). ## Reusing builds As already mentioned, ZenML will find an existing build if it matches your pipeline and stack, by itself. However, you can also force it to use a specific build by [passing the build ID](../../pipeline-development/use-configuration-files/what-can-be-configured.md#build-id) to the `build` parameter of the pipeline configuration. While reusing Docker builds is useful, it can be limited. This is because specifying a custom build when running a pipeline will **not run the code on your client machine** but will use the code **included in the Docker images of the build**. As a consequence, even if you make local code changes, reusing a build will _always_ execute the code bundled in the Docker image, rather than the local code. Therefore, if you would like to reuse a Docker build AND make sure your local code changes are also downloaded into the image, you need to disconnect your code from the build. You can do this either by registering a code repository or by letting ZenML use the artifact store to upload your code. ## Use the artifact store to upload your code You can also let ZenML use the artifact store to upload your code. This is the default behavior if no code repository is detected and the `allow_download_from_artifact_store` flag is not set to `False` in your `DockerSettings`. ## Use code repositories to speed up Docker build times One way to speed up Docker builds is to connect a git repository. Registering a [code repository](../../user-guide/production-guide/connect-code-repository.md) lets you avoid building images each time you run a pipeline **and** quickly iterate on your code. When running a pipeline that is part of a local code repository checkout, ZenML can instead build the Docker images without including any of your source files, and download the files inside the container before running your code. This greatly speeds up the building process and also allows you to reuse images that one of your colleagues might have built for the same stack. ZenML will **automatically figure out which builds match your pipeline and reuse the appropriate build id**. Therefore, you **do not** need to explicitly pass in the build id when you have a clean repository state and a connected git repository. This approach is **highly recommended**. See an end to end example [here](../../user-guide/production-guide/connect-code-repository.md). {% hint style="warning" %} In order to benefit from the advantages of having a code repository in a project, you need to make sure that **the relevant integrations are installed for your ZenML installation.**. For instance, let's assume you are working on a project with ZenML and one of your team members has already registered a corresponding code repository of type `github` for it. If you do `zenml code-repository list`, you would also be able to see this repository. However, in order to fully use this repository, you still need to install the corresponding integration for it, in this example the `github` integration. ```sh zenml integration install github ``` {% endhint %} ### Detecting local code repository checkouts Once you have registered one or more code repositories, ZenML will check whether the files you use when running a pipeline are tracked inside one of those code repositories. This happens as follows: * First, the [source root](./which-files-are-built-into-the-image.md) is computed * Next, ZenML checks whether this source root directory is included in a local checkout of one of the registered code repositories ### Tracking code versions for pipeline runs If a [local code repository checkout](#detecting-local-code-repository-checkouts) is detected when running a pipeline, ZenML will store a reference to the current commit for the pipeline run, so you'll be able to know exactly which code was used. Note that this reference is only tracked if your local checkout is clean (i.e. it does not contain any untracked or uncommitted files). This is to ensure that your pipeline is actually running with the exact code stored at the specific code repository commit. ### Tips and best practices It is also important to take some additional points into consideration: * The file download is only possible if the local checkout is clean (i.e. it does not contain any untracked or uncommitted files) and the latest commit has been pushed to the remote repository. This is necessary as otherwise, the file download inside the Docker container will fail. * If you want to disable or enforce the downloading of files, check out [this docs page](./docker-settings-on-a-pipeline.md) for the available options.
ZenML Scarf
================ File: docs/book/how-to/customize-docker-builds/how-to-use-a-private-pypi-repository.md ================ --- description: How to use a private PyPI repository. --- # How to use a private PyPI repository For packages that require authentication, you may need to take additional steps: 1. Use environment variables to store credentials securely. 2. Configure pip or poetry to use these credentials when installing packages. 3. Consider using custom Docker images that have the necessary authentication setup. Here's an example of how you might set up authentication using environment variables: ```python import os from my_simple_package import important_function from zenml.config import DockerSettings from zenml import step, pipeline docker_settings = DockerSettings( requirements=["my-simple-package==0.1.0"], environment={'PIP_EXTRA_INDEX_URL': f"https://{os.environ.get('PYPI_TOKEN', '')}@my-private-pypi-server.com/{os.environ.get('PYPI_USERNAME', '')}/"} ) @step def my_step(): return important_function() @pipeline(settings={"docker": docker_settings}) def my_pipeline(): my_step() if __name__ == "__main__": my_pipeline() ``` Note: Be cautious with handling credentials. Always use secure methods to manage and distribute authentication information within your team.
ZenML Scarf
================ File: docs/book/how-to/customize-docker-builds/README.md ================ --- icon: docker description: Using Docker images to run your pipeline. --- # Customize Docker Builds ZenML executes pipeline steps sequentially in the active Python environment when running locally. However, with remote [orchestrators](../../user-guide/production-guide/cloud-orchestration.md) or [step operators](../../component-guide/step-operators/step-operators.md), ZenML builds [Docker](https://www.docker.com/) images to run your pipeline in an isolated, well-defined environment. This section discusses how to control this dockerization process.
ZenML Scarf
================ File: docs/book/how-to/customize-docker-builds/specify-pip-dependencies-and-apt-packages.md ================ # Specify pip dependencies and apt packages {% hint style="warning" %} The configuration for specifying pip and apt dependencies only works in the remote pipeline case, and is disregarded for local pipelines (i.e. pipelines that run locally without having to build a Docker image). {% endhint %} When a [pipeline is run with a remote orchestrator](../pipeline-development/configure-python-environments/README.md) a [Dockerfile](https://docs.docker.com/engine/reference/builder/) is dynamically generated at runtime. It is then used to build the Docker image using the [image builder](../pipeline-development/configure-python-environments/README.md#-configure-python-environments) component of your stack. For all of examples on this page, note that `DockerSettings` can be imported using `from zenml.config import DockerSettings`. By default, ZenML automatically installs all packages required by your active ZenML stack. However, you can specify additional packages to be installed in various ways: * Install all the packages in your local Python environment (This will use the `pip` or `poetry` package manager to get a list of your local packages): ```python # or use "poetry_export" docker_settings = DockerSettings(replicate_local_python_environment="pip_freeze") @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` If required, a custom command can be provided. This command must output a list of requirements following the format of the [requirements file](https://pip.pypa.io/en/stable/reference/requirements-file-format/): ```python from zenml.config import DockerSettings docker_settings = DockerSettings(replicate_local_python_environment=[ "poetry", "export", "--extras=train", "--format=requirements.txt" ]) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` * Specify a list of requirements in code: ```python docker_settings = DockerSettings(requirements=["torch==1.12.0", "torchvision"]) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` * Specify a requirements file: ```python docker_settings = DockerSettings(requirements="/path/to/requirements.txt") @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` * Specify a list of [ZenML integrations](../../component-guide/README.md) that you're using in your pipeline: ```python from zenml.integrations.constants import PYTORCH, EVIDENTLY docker_settings = DockerSettings(required_integrations=[PYTORCH, EVIDENTLY]) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` * Specify a list of apt packages in code: ```python docker_settings = DockerSettings(apt_packages=["git"]) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` * Prevent ZenML from automatically installing the requirements of your stack: ```python docker_settings = DockerSettings(install_stack_requirements=False) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` * In some cases the steps of your pipeline will have conflicting requirements or some steps of your pipeline will require large dependencies that don't need to be installed to run the remaining steps of your pipeline. For this case, ZenML allows you to specify custom Docker settings for steps in your pipeline. ```python docker_settings = DockerSettings(requirements=["tensorflow"]) @step(settings={"docker": docker_settings}) def my_training_step(...): ... ``` {% hint style="info" %} You can combine these methods but do make sure that your list of requirements does not overlap with the ones specified explicitly in the Docker settings. {% endhint %} Depending on the options specified in your Docker settings, ZenML installs the requirements in the following order (each step optional): * The packages installed in your local python environment * The packages required by the stack unless this is disabled by setting `install_stack_requirements=False`. * The packages specified via the `required_integrations` * The packages specified via the `requirements` attribute * You can specify additional arguments for the installer used to install your Python packages as follows: ```python # This will result in a `pip install --timeout=1000 ...` call when installing packages in the # Docker image docker_settings = DockerSettings(python_package_installer_args={"timeout": 1000}) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` * **Experimental**: If you want to use [`uv`](https://github.com/astral-sh/uv) for faster resolving and installation of your Python packages, you can use by it as follows: ```python docker_settings = DockerSettings(python_package_installer="uv") @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` {% hint style="info" %} `uv` is a relatively new project and not as stable as `pip` yet, which might lead to errors during package installation. If this happens, try switching the installer back to `pip` and see if that solves the issue. {% endhint %} Full documentation for how `uv` 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.
ZenML Scarf
================ File: docs/book/how-to/customize-docker-builds/use-a-prebuilt-image.md ================ --- description: "Skip building an image for your ZenML pipeline altogether." --- # Use a prebuilt image for pipeline execution When running a pipeline on a remote Stack, ZenML builds a Docker image with a base ZenML image and adds all of your project dependencies to it. Optionally, if a code repository is not registered and `allow_download_from_artifact_store` is not set to `True` in your `DockerSettings`, ZenML will also add your pipeline code to the image. This process might take significant time depending on how big your dependencies are, how powerful your local system is and how fast your internet connection is. This is because Docker must pull base layers and push the final image to your container registry. Although this process only happens once and is skipped if ZenML detects no change in your environment, it might still be a bottleneck slowing down your pipeline execution. To save time and costs, you can choose to not build a Docker image every time your pipeline runs. This guide shows you how to do it using a prebuilt image, what you should include in your image for the pipeline to run successfully and other tips. {% hint style="info" %} Note that using this feature means that you won't be able to leverage any updates you make to your code or dependencies, outside of what your image already contains. {% endhint %} ## How do you use this feature The [`DockerSettings`](./docker-settings-on-a-pipeline.md#specify-docker-settings-for-a-pipeline) class in ZenML allows you to set a parent image to be used in your pipeline runs and gives the ability to skip building an image on top of it. To do this, just set the `parent_image` attribute of the `DockerSettings` class to the image you want to use and set `skip_build` to `True`. ```python docker_settings = DockerSettings( parent_image="my_registry.io/image_name:tag", skip_build=True ) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` {% hint style="warning" %} You should make sure that this image is pushed to a registry from which the orchestrator/step operator/other components that require the image can pull, without any involvement by ZenML. {% endhint %} ## What the parent image should contain When you run a pipeline with a pre-built image, skipping the build process, ZenML will not build any image on top of it. This means that the image you provide to the `parent_image` attribute of the `DockerSettings` class has to contain all the dependencies that are needed to run your pipeline, and optionally any code files if you don't have a code repository registered, and the `allow_download_from_artifact_store` flag is set to `False`. {% hint style="info" %} Note that this is different from the case where you [only specify a parent image](./docker-settings-on-a-pipeline.md#using-a-pre-built-parent-image) and don't want to `skip_build`. In the latter, ZenML still builds the image but does it on top of your parent image and not the base ZenML image. {% endhint %} {% hint style="info" %} If you're using an image that was already built by ZenML in a previous pipeline run, you don't need to worry about what goes in it as long as it was built for the **same stack** as your current pipeline run. You can use it directly. {% endhint %} The following points are derived from how ZenML builds an image internally and will help you make your own images. ### Your stack requirements A ZenML Stack can have different components and each comes with its own requirements. You need to ensure that your image contains them. The following is how you can get a list of stack requirements. ```python from zenml.client import Client stack_name = # set your stack as active if it isn't already Client().set_active_stack(stack_name) # get the requirements for the active stack active_stack = Client().active_stack stack_requirements = active_stack.requirements() ``` ### Integration requirements For all integrations that you use in your pipeline, you need to have their dependencies installed too. You can get a list of them in the following way: ```python from zenml.integrations.registry import integration_registry from zenml.integrations.constants import HUGGINGFACE, PYTORCH # define a list of all required integrations required_integrations = [PYTORCH, HUGGINGFACE] # Generate requirements for all required integrations integration_requirements = set( itertools.chain.from_iterable( integration_registry.select_integration_requirements( integration_name=integration, target_os=OperatingSystemType.LINUX, ) for integration in required_integrations ) ) ``` ### Any project-specific requirements For any other dependencies that your project relies on, you can then install all of these different requirements through a line in your `Dockerfile` that looks like the following. It assumes you have accumulated all the requirements in one file. ```Dockerfile RUN pip install -r FILE ``` ### Any system packages If you have any `apt` packages that are needed for your application to function, be sure to include them too. This can be achieved in a `Dockerfile` as follows: ```Dockerfile RUN apt-get update && apt-get install -y --no-install-recommends YOUR_APT_PACKAGES ``` ### Your project code files The files containing your pipeline and step code and all other necessary functions should be available in your execution environment. - If you have a [code repository](../../user-guide/production-guide/connect-code-repository.md) registered, you don't need to include your code files in the image yourself. ZenML will download them from the repository to the appropriate location in the image. - If you don't have a code repository but `allow_download_from_artifact_store` is set to `True` in your `DockerSettings` (`True` by default), ZenML will upload your code to the artifact store and make it available to the image. - If both of these options are disabled, you can include your code files in the image yourself. This approach is not recommended and you should use one of the above options. Take a look at [which files are built into the image](./which-files-are-built-into-the-image.md) page to learn more about what to include. Make sure that your code is in the `/app` directory and that this is set as the active working directory. {% hint style="info" %} Note that you also need Python, `pip` and `zenml` installed in your image. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/customize-docker-builds/use-your-own-docker-files.md ================ # Use your own Docker files In some cases, you might not want full control over the resulting Docker image but want to build a parent image dynamically each time a pipeline is executed. To make this process easier, ZenML allows you to specify a custom Dockerfile as well as `build context` directory and build options. ZenML then builds an intermediate image based on the Dockerfile you specified and uses the intermediate image as the parent image. Here is how the build process looks like: * **No `Dockerfile` specified**: If any of the options regarding requirements, environment variables or copying files require us to build an image, ZenML will build this image. Otherwise the `parent_image` will be used to run the pipeline. * **`Dockerfile` specified**: ZenML will first build an image based on the specified `Dockerfile`. If any of the options regarding requirements, environment variables or copying files require an additional image built on top of that, ZenML will build a second image. If not, the image build from the specified `Dockerfile` will be used to run the pipeline. Depending on the configuration of the [`DockerSettings`](https://sdkdocs.zenml.io/latest/core_code_docs/core-config/#zenml.config.docker_settings.DockerSettings) object, requirements will be installed in the following order (each step optional): * The packages installed in your local Python environment. * The packages specified via the `requirements` attribute. * The packages specified via the `required_integrations` and potentially stack requirements. {% hint style="info" %} Depending on the configuration of your Docker settings, this intermediate image might also be used directly to execute your pipeline steps. {% endhint %} ```python docker_settings = DockerSettings( dockerfile="/path/to/dockerfile", build_context_root="/path/to/build/context", parent_image_build_config={ "build_options": ... "dockerignore": ... } ) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ```
ZenML Scarf
================ File: docs/book/how-to/customize-docker-builds/which-files-are-built-into-the-image.md ================ # Which files are built into the image ZenML determines the root directory of your source files in the following order: * If you've initialized zenml (`zenml init`) in your current working directory or one of its parent directories, the repository root directory will be used. * Otherwise, the parent directory of the Python file you're executing will be the source root. For example, running `python /path/to/file.py`, the source root would be `/path/to`. You can specify how the files inside this root directory are handled using the following three attributes on the [DockerSettings](https://sdkdocs.zenml.io/latest/core_code_docs/core-config/#zenml.config.docker_settings.DockerSettings): * `allow_download_from_code_repository`: If this is set to `True` and your files are inside a registered [code repository](../../user-guide/production-guide/connect-code-repository.md) and the repository has no local changes, the files will be downloaded from the code repository and not included in the image. * `allow_download_from_artifact_store`: If the previous option is disabled or no code repository without local changes exists for the root directory, ZenML will archive and upload your code to the artifact store if this is set to `True`. * `allow_including_files_in_images`: If both previous options were disabled or not possible, ZenML will include your files in the Docker image if this option is enabled. This means a new Docker image has to be built each time you modify one of your code files. {% hint style="warning" %} Setting all of the above attributes to `False` is not recommended and will most likely cause unintended and unanticipated behavior when running your pipelines. If you do this, you're responsible that all your files are at the correct paths in the Docker images that will be used to run your pipeline steps. {% endhint %} ## Control which files get downloaded When downloading files either from a code repository or the artifact store, ZenML downloads all contents of the root directory into the Docker container. To exclude files, track your code in a Git repository use a [gitignore](https://git-scm.com/docs/gitignore/en) to specify which files should be excluded. ## Control which files get included When including files in the image, ZenML copies all contents of the root directory into the Docker image. To exclude files and keep the image smaller, use a [.dockerignore file](https://docs.docker.com/engine/reference/builder/#dockerignore-file) in either of the following ways: * Have a file called `.dockerignore` in your source root directory. * Explicitly specify a `.dockerignore` file to use: ```python docker_settings = DockerSettings(build_config={"dockerignore": "/path/to/.dockerignore"}) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ```
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/complex-usecases/datasets.md ================ --- description: Model datasets using simple abstractions. --- # Custom Dataset Classes and Complex Data Flows in ZenML As machine learning projects grow in complexity, you often need to work with various data sources and manage intricate data flows. This chapter explores how to use custom Dataset classes and Materializers in ZenML to handle these challenges efficiently. For strategies on scaling your data processing for larger datasets, refer to [scaling strategies for big data](manage-big-data.md). ## Introduction to Custom Dataset Classes Custom Dataset classes in ZenML provide a way to encapsulate data loading, processing, and saving logic for different data sources. They're particularly useful when: 1. Working with multiple data sources (e.g., CSV files, databases, cloud storage) 2. Dealing with complex data structures that require special handling 3. Implementing custom data processing or transformation logic ## Implementing Dataset Classes for Different Data Sources Let's create a base Dataset class and implement it for CSV and BigQuery data sources: ```python from abc import ABC, abstractmethod import pandas as pd from google.cloud import bigquery from typing import Optional class Dataset(ABC): @abstractmethod def read_data(self) -> pd.DataFrame: pass class CSVDataset(Dataset): def __init__(self, data_path: str, df: Optional[pd.DataFrame] = None): self.data_path = data_path self.df = df def read_data(self) -> pd.DataFrame: if self.df is None: self.df = pd.read_csv(self.data_path) return self.df class BigQueryDataset(Dataset): def __init__( self, table_id: str, df: Optional[pd.DataFrame] = None, project: Optional[str] = None, ): self.table_id = table_id self.project = project self.df = df self.client = bigquery.Client(project=self.project) def read_data(self) -> pd.DataFrame: query = f"SELECT * FROM `{self.table_id}`" self.df = self.client.query(query).to_dataframe() return self.df def write_data(self) -> None: job_config = bigquery.LoadJobConfig(write_disposition="WRITE_TRUNCATE") job = self.client.load_table_from_dataframe(self.df, self.table_id, job_config=job_config) job.result() ``` ## Creating Custom Materializers [Materializers](../../../how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md) in ZenML handle the serialization and deserialization of artifacts. Custom Materializers are essential for working with custom Dataset classes: ```python from typing import Type from zenml.materializers import BaseMaterializer from zenml.io import fileio from zenml.enums import ArtifactType import json import os import tempfile import pandas as pd class CSVDatasetMaterializer(BaseMaterializer): ASSOCIATED_TYPES = (CSVDataset,) ASSOCIATED_ARTIFACT_TYPE = ArtifactType.DATA def load(self, data_type: Type[CSVDataset]) -> CSVDataset: # Create a temporary file to store the CSV data with tempfile.NamedTemporaryFile(delete=False, suffix='.csv') as temp_file: # Copy the CSV file from the artifact store to the temporary location with fileio.open(os.path.join(self.uri, "data.csv"), "rb") as source_file: temp_file.write(source_file.read()) temp_path = temp_file.name # Create and return the CSVDataset dataset = CSVDataset(temp_path) dataset.read_data() return dataset def save(self, dataset: CSVDataset) -> None: # Ensure we have data to save df = dataset.read_data() # Save the dataframe to a temporary CSV file with tempfile.NamedTemporaryFile(delete=False, suffix='.csv') as temp_file: df.to_csv(temp_file.name, index=False) temp_path = temp_file.name # Copy the temporary file to the artifact store with open(temp_path, "rb") as source_file: with fileio.open(os.path.join(self.uri, "data.csv"), "wb") as target_file: target_file.write(source_file.read()) # Clean up the temporary file os.remove(temp_path) class BigQueryDatasetMaterializer(BaseMaterializer): ASSOCIATED_TYPES = (BigQueryDataset,) ASSOCIATED_ARTIFACT_TYPE = ArtifactType.DATA def load(self, data_type: Type[BigQueryDataset]) -> BigQueryDataset: with fileio.open(os.path.join(self.uri, "metadata.json"), "r") as f: metadata = json.load(f) dataset = BigQueryDataset( table_id=metadata["table_id"], project=metadata["project"], ) dataset.read_data() return dataset def save(self, bq_dataset: BigQueryDataset) -> None: metadata = { "table_id": bq_dataset.table_id, "project": bq_dataset.project, } with fileio.open(os.path.join(self.uri, "metadata.json"), "w") as f: json.dump(metadata, f) if bq_dataset.df is not None: bq_dataset.write_data() ``` ## Managing Complexity in Pipelines with Multiple Data Sources When working with multiple data sources, it's crucial to design flexible pipelines that can handle different scenarios. Here's an example of how to structure a pipeline that works with both CSV and BigQuery datasets: ```python from zenml import step, pipeline from typing_extensions import Annotated @step(output_materializer=CSVDatasetMaterializer) def extract_data_local(data_path: str = "data/raw_data.csv") -> CSVDataset: return CSVDataset(data_path) @step(output_materializer=BigQueryDatasetMaterializer) def extract_data_remote(table_id: str) -> BigQueryDataset: return BigQueryDataset(table_id) @step def transform(dataset: Dataset) -> pd.DataFrame df = dataset.read_data() # Transform data transformed_df = df.copy() # Apply transformations here return transformed_df @pipeline def etl_pipeline(mode: str = "develop"): if mode == "develop": raw_data = extract_data_local() else: raw_data = extract_data_remote(table_id="project.dataset.raw_table") transformed_data = transform(raw_data) ``` ## Best Practices for Designing Flexible and Maintainable Pipelines When working with custom Dataset classes in ZenML pipelines, it's crucial to design your pipelines to accommodate various data sources and processing requirements. Here are some best practices to ensure your pipelines remain flexible and maintainable: 1. **Use a common base class**: The `Dataset` base class allows for consistent handling of different data sources within your pipeline steps. This abstraction enables you to swap out data sources without changing the overall pipeline structure. ```python @step def process_data(dataset: Dataset) -> pd.DataFrame: data = dataset.read_data() # Process data... return processed_data ``` 2. **Create specialized steps to load the right dataset**: Implement separate steps to load different datasets, while keeping underlying steps standardized. ```python @step def load_csv_data() -> CSVDataset: # CSV-specific processing pass @step def load_bigquery_data() -> BigQueryDataset: # BigQuery-specific processing pass @step def common_processing_step(dataset: Dataset) -> pd.DataFrame: # Loads the base dataset, does not know concrete type pass ``` 3. **Implement flexible pipelines**: Design your pipelines to adapt to different data sources or processing requirements. You can use configuration parameters or conditional logic to determine which steps to execute. ```python @pipeline def flexible_data_pipeline(data_source: str): if data_source == "csv": dataset = load_csv_data() elif data_source == "bigquery": dataset = load_bigquery_data() final_result = common_processing_step(dataset) return final_result ``` 4. **Modular step design**: Focus on creating steps that perform specific tasks (e.g., data loading, transformation, analysis) that can work with different dataset types. This promotes code reuse and ease of maintenance. ```python @step def transform_data(dataset: Dataset) -> pd.DataFrame: data = dataset.read_data() # Common transformation logic return transformed_data @step def analyze_data(data: pd.DataFrame) -> pd.DataFrame: # Common analysis logic return analysis_result ``` By following these practices, you can create ZenML pipelines that efficiently handle complex data flows and multiple data sources while remaining adaptable to changing requirements. This approach allows you to leverage the power of custom Dataset classes throughout your machine learning workflows, ensuring consistency and flexibility as your projects evolve. For strategies on scaling your data processing as your datasets grow larger, refer to [scaling strategies for big data](manage-big-data.md). ================ File: docs/book/how-to/data-artifact-management/complex-usecases/manage-big-data.md ================ --- description: Learn about how to manage big data with ZenML. --- # Scaling Strategies for Big Data in ZenML As your machine learning projects grow, you'll often encounter datasets that challenge your existing data processing pipelines. This section explores strategies for scaling your ZenML pipelines to handle increasingly large datasets. For information on creating custom Dataset classes and managing complex data flows, refer to [custom dataset classes](datasets.md). ## Understanding Dataset Size Thresholds Before diving into specific strategies, it's important to understand the general thresholds where different approaches become necessary: 1. **Small datasets (up to a few GB)**: These can typically be handled in-memory with standard pandas operations. 2. **Medium datasets (up to tens of GB)**: Require chunking or out-of-core processing techniques. 3. **Large datasets (hundreds of GB or more)**: Necessitate distributed processing frameworks. ## Strategies for Datasets up to a Few Gigabytes For datasets that can still fit in memory but are becoming unwieldy, consider these optimizations: 1. **Use efficient data formats**: Switch from CSV to more efficient formats like Parquet: ```python import pyarrow.parquet as pq class ParquetDataset(Dataset): def __init__(self, data_path: str): self.data_path = data_path def read_data(self) -> pd.DataFrame: return pq.read_table(self.data_path).to_pandas() def write_data(self, df: pd.DataFrame): table = pa.Table.from_pandas(df) pq.write_table(table, self.data_path) ``` 2. **Implement basic data sampling**: Add sampling methods to your Dataset classes: ```python import random class SampleableDataset(Dataset): def sample_data(self, fraction: float = 0.1) -> pd.DataFrame: df = self.read_data() return df.sample(frac=fraction) @step def analyze_sample(dataset: SampleableDataset) -> Dict[str, float]: sample = dataset.sample_data(fraction=0.1) # Perform analysis on the sample return {"mean": sample["value"].mean(), "std": sample["value"].std()} ``` 3. **Optimize pandas operations**: Use efficient pandas and numpy operations to minimize memory usage: ```python @step def optimize_processing(df: pd.DataFrame) -> pd.DataFrame: # Use inplace operations where possible df['new_column'] = df['column1'] + df['column2'] # Use numpy operations for speed df['mean_normalized'] = df['value'] - np.mean(df['value']) return df ``` ## Handling Datasets up to Tens of Gigabytes When your data no longer fits comfortably in memory, consider these strategies: ### Chunking for CSV Datasets Implement chunking in your Dataset classes to process large files in manageable pieces: ```python class ChunkedCSVDataset(Dataset): def __init__(self, data_path: str, chunk_size: int = 10000): self.data_path = data_path self.chunk_size = chunk_size def read_data(self): for chunk in pd.read_csv(self.data_path, chunksize=self.chunk_size): yield chunk @step def process_chunked_csv(dataset: ChunkedCSVDataset) -> pd.DataFrame: processed_chunks = [] for chunk in dataset.read_data(): processed_chunks.append(process_chunk(chunk)) return pd.concat(processed_chunks) def process_chunk(chunk: pd.DataFrame) -> pd.DataFrame: # Process each chunk here return chunk ``` ### Leveraging Data Warehouses for Large Datasets You can utilize data warehouses like [Google BigQuery](https://cloud.google.com/bigquery) for its distributed processing capabilities: ```python @step def process_big_query_data(dataset: BigQueryDataset) -> BigQueryDataset: client = bigquery.Client() query = f""" SELECT column1, AVG(column2) as avg_column2 FROM `{dataset.table_id}` GROUP BY column1 """ result_table_id = f"{dataset.project}.{dataset.dataset}.processed_data" job_config = bigquery.QueryJobConfig(destination=result_table_id) query_job = client.query(query, job_config=job_config) query_job.result() # Wait for the job to complete return BigQueryDataset(table_id=result_table_id) ``` ## Approaches for Very Large Datasets (Hundreds of Gigabytes or More): Using Distributed Computing Frameworks in ZenML When dealing with very large datasets, you may need to leverage distributed computing frameworks like Apache Spark or Ray. ZenML doesn't have built-in integrations for these frameworks, but you can use them directly within your pipeline steps. Here's how you can incorporate Spark and Ray into your ZenML pipelines: ### Using Apache Spark in ZenML To use Spark within a ZenML pipeline, you simply need to initialize and use Spark within your step function: ```python from pyspark.sql import SparkSession from zenml import step, pipeline @step def process_with_spark(input_data: str) -> None: # Initialize Spark spark = SparkSession.builder.appName("ZenMLSparkStep").getOrCreate() # Read data df = spark.read.format("csv").option("header", "true").load(input_data) # Process data using Spark result = df.groupBy("column1").agg({"column2": "mean"}) # Write results result.write.csv("output_path", header=True, mode="overwrite") # Stop the Spark session spark.stop() @pipeline def spark_pipeline(input_data: str): process_with_spark(input_data) # Run the pipeline spark_pipeline(input_data="path/to/your/data.csv") ``` Note that you'll need to have Spark installed in your environment and ensure that the necessary Spark dependencies are available when running your pipeline. ### Using Ray in ZenML Similarly, to use Ray within a ZenML pipeline, you can initialize and use Ray directly within your step: ```python import ray from zenml import step, pipeline @step def process_with_ray(input_data: str) -> None: ray.init() @ray.remote def process_partition(partition): # Process a partition of the data return processed_partition # Load and split your data data = load_data(input_data) partitions = split_data(data) # Distribute processing across Ray cluster results = ray.get([process_partition.remote(part) for part in partitions]) # Combine and save results combined_results = combine_results(results) save_results(combined_results, "output_path") ray.shutdown() @pipeline def ray_pipeline(input_data: str): process_with_ray(input_data) # Run the pipeline ray_pipeline(input_data="path/to/your/data.csv") ``` As with Spark, you'll need to have Ray installed in your environment and ensure that the necessary Ray dependencies are available when running your pipeline. ### Using Dask in ZenML [Dask](https://docs.dask.org/en/stable/) is a flexible library for parallel computing in Python. It can be integrated into ZenML pipelines to handle large datasets and parallelize computations. Here's how you can use Dask within a ZenML pipeline: ```python from zenml import step, pipeline import dask.dataframe as dd from zenml.materializers.base_materializer import BaseMaterializer import os class DaskDataFrameMaterializer(BaseMaterializer): ASSOCIATED_TYPES = (dd.DataFrame,) ASSOCIATED_ARTIFACT_TYPE = "dask_dataframe" def load(self, data_type): return dd.read_parquet(os.path.join(self.uri, "data.parquet")) def save(self, data): data.to_parquet(os.path.join(self.uri, "data.parquet")) @step(output_materializers=DaskDataFrameMaterializer) def create_dask_dataframe(): df = dd.from_pandas(pd.DataFrame({'A': range(1000), 'B': range(1000, 2000)}), npartitions=4) return df @step def process_dask_dataframe(df: dd.DataFrame) -> dd.DataFrame: result = df.map_partitions(lambda x: x ** 2) return result @step def compute_result(df: dd.DataFrame) -> pd.DataFrame: return df.compute() @pipeline def dask_pipeline(): df = create_dask_dataframe() processed = process_dask_dataframe(df) result = compute_result(processed) # Run the pipeline dask_pipeline() ``` In this example, we've created a custom `DaskDataFrameMaterializer` to handle Dask DataFrames. The pipeline creates a Dask DataFrame, processes it using Dask's distributed computing capabilities, and then computes the final result. ### Using Numba in ZenML [Numba](https://numba.pydata.org/) is a just-in-time compiler for Python that can significantly speed up numerical Python code. Here's how you can integrate Numba into a ZenML pipeline: ```python from zenml import step, pipeline import numpy as np from numba import jit import os @jit(nopython=True) def numba_function(x): return x * x + 2 * x - 1 @step def load_data() -> np.ndarray: return np.arange(1000000) @step def apply_numba_function(data: np.ndarray) -> np.ndarray: return numba_function(data) @pipeline def numba_pipeline(): data = load_data() result = apply_numba_function(data) # Run the pipeline numba_pipeline() ``` The pipeline creates a Numba-accelerated function, applies it to a large NumPy array, and returns the result. ### Important Considerations 1. **Environment Setup**: Ensure that your execution environment (local or remote) has the necessary frameworks (Spark or Ray) installed. 2. **Resource Management**: When using these frameworks within ZenML steps, be mindful of resource allocation. The frameworks will manage their own resources, which needs to be coordinated with ZenML's orchestration. 3. **Error Handling**: Implement proper error handling and cleanup, especially for shutting down Spark sessions or Ray runtime. 4. **Data I/O**: Consider how data will be passed into and out of the distributed processing step. You might need to use intermediate storage (like cloud storage) for large datasets. 5. **Scaling**: While these frameworks allow for distributed processing, you'll need to ensure your infrastructure can support the scale of computation you're attempting. By incorporating Spark or Ray directly into your ZenML steps, you can leverage the power of distributed computing for processing very large datasets while still benefiting from ZenML's pipeline management and versioning capabilities. ## Choosing the Right Scaling Strategy When selecting a scaling strategy, consider: 1. **Dataset size**: Start with simpler strategies for smaller datasets and move to more complex solutions as your data grows. 2. **Processing complexity**: Simple aggregations might be handled by BigQuery, while complex ML preprocessing might require Spark or Ray. 3. **Infrastructure and resources**: Ensure you have the necessary compute resources for distributed processing. 4. **Update frequency**: Consider how often your data changes and how frequently you need to reprocess it. 5. **Team expertise**: Choose technologies that your team is comfortable with or can quickly learn. Remember, it's often best to start simple and scale up as needed. ZenML's flexible architecture allows you to evolve your data processing strategies as your project grows. By implementing these scaling strategies, you can extend your ZenML pipelines to handle datasets of any size, ensuring that your machine learning workflows remain efficient and manageable as your projects scale. For more information on creating custom Dataset classes and managing complex data flows, refer back to [custom dataset classes](datasets.md). ================ File: docs/book/how-to/data-artifact-management/complex-usecases/passing-artifacts-between-pipelines.md ================ --- description: Structuring an MLOps project --- # Passing artifacts between pipelines An MLOps project can often be broken down into many different pipelines. For example: * A feature engineering pipeline that prepares raw data into a format ready to get trained. * A training pipeline that takes input data from a feature engineering pipeline and trains a models on it. * An inference pipeline that runs batch predictions on the trained model and often takes pre-processing from the training pipeline. * A deployment pipeline that deploys a trained model into a production endpoint. The lines between these pipelines can often get blurry: Some use cases call for these pipelines to be merged into one big pipeline. Others go further and break the pipeline down into even smaller chunks. Ultimately, the decision of how to structure your pipelines depends on the use case and requirements of the project. No matter how you design these pipelines, one thing stays consistent: you will often need to transfer or share information (in particular artifacts, models, and metadata) between pipelines. Here are some common patterns that you can use to help facilitate such an exchange: ## Pattern 1: Artifact exchange between pipelines through `Client` Let's say we have a feature engineering pipeline and a training pipeline. The feature engineering pipeline is like a factory, pumping out many different datasets. Only a few of these datasets should be selected to be sent to the training pipeline to train an actual model.

A simple artifact exchange between two pipelines

In this scenario, the [ZenML Client](../../../reference/python-client.md#client-methods) can be used to facilitate such an exchange: ```python from zenml import pipeline from zenml.client import Client @pipeline def feature_engineering_pipeline(): dataset = load_data() # This returns artifacts called "iris_training_dataset" and "iris_testing_dataset" train_data, test_data = prepare_data() @pipeline def training_pipeline(): client = Client() # Fetch by name alone - uses the latest version of this artifact train_data = client.get_artifact_version(name="iris_training_dataset") # For test, we want a particular version test_data = client.get_artifact_version(name="iris_testing_dataset", version="raw_2023") # We can now send these directly into ZenML steps sklearn_classifier = model_trainer(train_data) model_evaluator(model, sklearn_classifier) ``` {% hint style="info" %} Note that in the above example, the `train_data` and `test_data` artifacts are not [materialized](../../../how-to/data-artifact-management/handle-data-artifacts/artifact-versioning.md) in memory in the `@pipeline` function, but rather the `train_data` and `test_data` objects are simply references to where this data is stored in the artifact store. Therefore, one cannot use any logic regarding the nature of this data itself during compilation time (i.e. in the `@pipeline` function). {% endhint %} ## Pattern 2: Artifact exchange between pipelines through a `Model` While passing around artifacts with IDs or names is very useful, it is often desirable to have the ZenML Model be the point of reference instead. For example, let's say we have a training pipeline called `train_and_promote` and an inference pipeline called `do_predictions`. The training pipeline produces many different model artifacts, all of which are collected within a [ZenML Model](../../../user-guide/starter-guide/track-ml-models.md). Each time the `train_and_promote` pipeline runs, it creates a new `iris_classifier`. However, it only promotes the model to `production` if a certain accuracy threshold is met. The promotion can be also be done manually with human intervention, or it can be automated through setting a particular threshold. On the other side, the `do_predictions` pipeline simply picks up the latest promoted model and runs batch inference on it. It need not know of the IDs or names of any of the artifacts produced by the training pipeline's many runs. This way these two pipelines can independently be run, but can rely on each other's output.

A simple artifact exchange between pipelines through the Model Control Plane.

In code, this is very simple. Once the [pipelines are configured to use a particular model](../../../user-guide/starter-guide/track-ml-models.md#configuring-a-model-in-a-pipeline), we can use `get_step_context` to fetch the configured model within a step directly. Assuming there is a `predict` step in the `do_predictions` pipeline, we can fetch the `production` model like so: ```python from zenml import step, get_step_context # IMPORTANT: Cache needs to be disabled to avoid unexpected behavior @step(enable_cache=False) def predict( data: pd.DataFrame, ) -> Annotated[pd.Series, "predictions"]: # model name and version are derived from pipeline context model = get_step_context().model # Fetch the model directly from the model control plane model = model.get_model_artifact("trained_model") # Make predictions predictions = pd.Series(model.predict(data)) return predictions ``` However, this approach has the downside that if the step is cached, then it could lead to unexpected results. You could simply disable the cache in the above step or the corresponding pipeline. However, one other way of achieving this would be to resolve the artifact at the pipeline level: ```python from typing_extensions import Annotated from zenml import get_pipeline_context, pipeline, Model from zenml.enums import ModelStages import pandas as pd from sklearn.base import ClassifierMixin @step def predict( model: ClassifierMixin, data: pd.DataFrame, ) -> Annotated[pd.Series, "predictions"]: predictions = pd.Series(model.predict(data)) return predictions @pipeline( model=Model( name="iris_classifier", # Using the production stage version=ModelStages.PRODUCTION, ), ) def do_predictions(): # model name and version are derived from pipeline context model = get_pipeline_context().model inference_data = load_data() predict( # Here, we load in the `trained_model` from a trainer step model=model.get_model_artifact("trained_model"), data=inference_data, ) if __name__ == "__main__": do_predictions() ``` Ultimately, both approaches are fine. You should decide which one to use based on your own preferences.
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/complex-usecases/README.md ================ --- icon: sitemap --- ================ File: docs/book/how-to/data-artifact-management/complex-usecases/registering-existing-data.md ================ --- description: Learn how to register an external data as a ZenML artifact for future use. --- # Register Existing Data as a ZenML Artifact Many modern Machine Learning framework create their own data as a byproduct of model training or other processes. In such cases there is no need to read and materialize those data assets to pack them into a ZenML Artifact, instead it is beneficial registering those data assets as-is in ZenML for future use. ## Register Existing Folder as a ZenML Artifact If the data created externally is a folder you can register the whole folder as a ZenML Artifact and later make use of it in subsequent steps or other pipelines. ```python import os from uuid import uuid4 from pathlib import Path from zenml.client import Client from zenml import register_artifact prefix = Client().active_stack.artifact_store.path test_file_name = "test_file.txt" preexisting_folder = os.path.join(prefix,f"my_test_folder_{uuid4()}") preexisting_file = os.path.join(preexisting_folder,test_file_name) # produce a folder with a file inside artifact store boundaries os.mkdir(preexisting_folder) with open(preexisting_file,"w") as f: f.write("test") # create artifact from the preexisting folder register_artifact( folder_or_file_uri=preexisting_folder, name="my_folder_artifact" ) # consume artifact as a folder temp_artifact_folder_path = Client().get_artifact_version(name_id_or_prefix="my_folder_artifact").load() assert isinstance(temp_artifact_folder_path, Path) assert os.path.isdir(temp_artifact_folder_path) with open(os.path.join(temp_artifact_folder_path,test_file_name),"r") as f: assert f.read() == "test" ``` {% hint style="info" %} The artifact produced from the preexisting data will have a `pathlib.Path` type, once loaded or passed as input to another step. The path will be pointing to a temporary location in the executing environment and ready for use as a normal local `Path` (passed into `from_pretrained` or `open` functions to name a few examples). {% endhint %} ## Register Existing File as a ZenML Artifact If the data created externally is a file you can register it as a ZenML Artifact and later make use of it in subsequent steps or other pipelines. ```python import os from uuid import uuid4 from pathlib import Path from zenml.client import Client from zenml import register_artifact prefix = Client().active_stack.artifact_store.path test_file_name = "test_file.txt" preexisting_folder = os.path.join(prefix,f"my_test_folder_{uuid4()}") preexisting_file = os.path.join(preexisting_folder,test_file_name) # produce a file inside artifact store boundaries os.mkdir(preexisting_folder) with open(preexisting_file,"w") as f: f.write("test") # create artifact from the preexisting file register_artifact( folder_or_file_uri=preexisting_file, name="my_file_artifact" ) # consume artifact as a file temp_artifact_file_path = Client().get_artifact_version(name_id_or_prefix="my_file_artifact").load() assert isinstance(temp_artifact_file_path, Path) assert not os.path.isdir(temp_artifact_file_path) with open(temp_artifact_file_path,"r") as f: assert f.read() == "test" ``` ## Register All Checkpoints of a Pytorch Lightning Training Run Now let's explore the Pytorch Lightning example to fit the model and store the checkpoints in a remote location. ```python import os from zenml.client import Client from zenml import register_artifact from pytorch_lightning import Trainer from pytorch_lightning.callbacks import ModelCheckpoint from uuid import uuid4 # Define where the model data should be saved # use active ArtifactStore prefix = Client().active_stack.artifact_store.path # keep data separable for future runs with uuid4 folder default_root_dir = os.path.join(prefix, uuid4().hex) # Define the model and fit it model = ... trainer = Trainer( default_root_dir=default_root_dir, callbacks=[ ModelCheckpoint( every_n_epochs=1, save_top_k=-1, filename="checkpoint-{epoch:02d}" ) ], ) try: trainer.fit(model) finally: # We now link those checkpoints in ZenML as an artifact # This will create a new artifact version register_artifact(default_root_dir, name="all_my_model_checkpoints") ``` Even if an artifact is created and stored externally, it can be treated like any other artifact produced by ZenML steps - with all the functionalities described above! ## Register Checkpoints of a Pytorch Lightning Training Run as Separate Artifact Versions To make checkpoints (or other intermediate artifacts) linkage better versioned you can extend the `ModelCheckpoint` callback to your needs. For example such custom implementation could look like the one below, where we extend the `on_train_epoch_end` method to register each checkpoint created during the training as a separate Artifact Version in ZenML. {% hint style="warning" %} To make checkpoint files last you need to set `save_top_k=-1`, otherwise older checkpoints will be deleted, making registered artifact version unusable. {% endhint %} ```python import os from zenml.client import Client from zenml import register_artifact from zenml import get_step_context from zenml.exceptions import StepContextError from zenml.logger import get_logger from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning import Trainer, LightningModule logger = get_logger(__name__) class ZenMLModelCheckpoint(ModelCheckpoint): """A ModelCheckpoint that can be used with ZenML. Used to store model checkpoints in ZenML as artifacts. Supports `default_root_dir` to pass into `Trainer`. """ def __init__( self, artifact_name: str, every_n_epochs: int = 1, save_top_k: int = -1, *args, **kwargs, ): # get all needed info for the ZenML logic try: zenml_model = get_step_context().model except StepContextError: raise RuntimeError( "`ZenMLModelCheckpoint` can only be called from within a step." ) model_name = zenml_model.name filename = model_name + "_{epoch:02d}" self.filename_format = model_name + "_epoch={epoch:02d}.ckpt" self.artifact_name = artifact_name prefix = Client().active_stack.artifact_store.path self.default_root_dir = os.path.join(prefix, str(zenml_model.version)) logger.info(f"Model data will be stored in {self.default_root_dir}") super().__init__( every_n_epochs=every_n_epochs, save_top_k=save_top_k, filename=filename, *args, **kwargs, ) def on_train_epoch_end( self, trainer: "Trainer", pl_module: "LightningModule" ) -> None: super().on_train_epoch_end(trainer, pl_module) # We now link those checkpoints in ZenML as an artifact # This will create a new artifact version register_artifact( os.path.join( self.dirpath, self.filename_format.format(epoch=trainer.current_epoch) ), self.artifact_name, ) ``` Below you can find a sophisticated example of a pipeline doing a Pytorch Lightning training with the artifacts linkage for checkpoint artifacts implemented as an extended Callback.
Pytorch Lightning training with the checkpoints linkage full example ```python import os from typing import Annotated from pathlib import Path import numpy as np from zenml.client import Client from zenml import register_artifact from zenml import step, pipeline, get_step_context, Model from zenml.exceptions import StepContextError from zenml.logger import get_logger from torch.utils.data import DataLoader from torch.nn import ReLU, Linear, Sequential from torch.nn.functional import mse_loss from torch.optim import Adam from torch import rand from torchvision.datasets import MNIST from torchvision.transforms import ToTensor from pytorch_lightning.callbacks import ModelCheckpoint from pytorch_lightning import Trainer, LightningModule from zenml.new.pipelines.pipeline_context import get_pipeline_context logger = get_logger(__name__) class ZenMLModelCheckpoint(ModelCheckpoint): """A ModelCheckpoint that can be used with ZenML. Used to store model checkpoints in ZenML as artifacts. Supports `default_root_dir` to pass into `Trainer`. """ def __init__( self, artifact_name: str, every_n_epochs: int = 1, save_top_k: int = -1, *args, **kwargs, ): # get all needed info for the ZenML logic try: zenml_model = get_step_context().model except StepContextError: raise RuntimeError( "`ZenMLModelCheckpoint` can only be called from within a step." ) model_name = zenml_model.name filename = model_name + "_{epoch:02d}" self.filename_format = model_name + "_epoch={epoch:02d}.ckpt" self.artifact_name = artifact_name prefix = Client().active_stack.artifact_store.path self.default_root_dir = os.path.join(prefix, str(zenml_model.version)) logger.info(f"Model data will be stored in {self.default_root_dir}") super().__init__( every_n_epochs=every_n_epochs, save_top_k=save_top_k, filename=filename, *args, **kwargs, ) def on_train_epoch_end( self, trainer: "Trainer", pl_module: "LightningModule" ) -> None: super().on_train_epoch_end(trainer, pl_module) # We now link those checkpoints in ZenML as an artifact # This will create a new artifact version register_artifact( os.path.join( self.dirpath, self.filename_format.format(epoch=trainer.current_epoch) ), self.artifact_name, ) # define the LightningModule toy model class LitAutoEncoder(LightningModule): def __init__(self, encoder, decoder): super().__init__() self.encoder = encoder self.decoder = decoder def training_step(self, batch, batch_idx): # training_step defines the train loop. # it is independent of forward x, _ = batch x = x.view(x.size(0), -1) z = self.encoder(x) x_hat = self.decoder(z) loss = mse_loss(x_hat, x) # Logging to TensorBoard (if installed) by default self.log("train_loss", loss) return loss def configure_optimizers(self): optimizer = Adam(self.parameters(), lr=1e-3) return optimizer @step def get_data() -> DataLoader: """Get the training data.""" dataset = MNIST(os.getcwd(), download=True, transform=ToTensor()) train_loader = DataLoader(dataset) return train_loader @step def get_model() -> LightningModule: """Get the model to train.""" encoder = Sequential(Linear(28 * 28, 64), ReLU(), Linear(64, 3)) decoder = Sequential(Linear(3, 64), ReLU(), Linear(64, 28 * 28)) model = LitAutoEncoder(encoder, decoder) return model @step def train_model( model: LightningModule, train_loader: DataLoader, epochs: int = 1, artifact_name: str = "my_model_ckpts", ) -> None: """Run the training loop.""" # configure checkpointing chkpt_cb = ZenMLModelCheckpoint(artifact_name=artifact_name) trainer = Trainer( # pass default_root_dir from ZenML checkpoint to # ensure that the data is accessible for the artifact # store default_root_dir=chkpt_cb.default_root_dir, limit_train_batches=100, max_epochs=epochs, callbacks=[chkpt_cb], ) trainer.fit(model, train_loader) @step def predict( checkpoint_file: Path, ) -> Annotated[np.ndarray, "predictions"]: # load the model from the checkpoint encoder = Sequential(Linear(28 * 28, 64), ReLU(), Linear(64, 3)) decoder = Sequential(Linear(3, 64), ReLU(), Linear(64, 28 * 28)) autoencoder = LitAutoEncoder.load_from_checkpoint( checkpoint_file, encoder=encoder, decoder=decoder ) encoder = autoencoder.encoder encoder.eval() # predict on fake batch fake_image_batch = rand(4, 28 * 28, device=autoencoder.device) embeddings = encoder(fake_image_batch) if embeddings.device.type == "cpu": return embeddings.detach().numpy() else: return embeddings.detach().cpu().numpy() @pipeline(model=Model(name="LightningDemo")) def train_pipeline(artifact_name: str = "my_model_ckpts"): train_loader = get_data() model = get_model() train_model(model, train_loader, 10, artifact_name) # pass in the latest checkpoint for predictions predict( get_pipeline_context().model.get_artifact(artifact_name), after=["train_model"] ) if __name__ == "__main__": train_pipeline() ```
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/complex-usecases/unmaterialized-artifacts.md ================ --- description: Skip materialization of artifacts. --- # Unmaterialized artifacts A ZenML pipeline is built in a data-centric way. The outputs and inputs of steps define how steps are connected and the order in which they are executed. Each step should be considered as its very own process that reads and writes its inputs and outputs from and to the [artifact store](../../../component-guide/artifact-stores/artifact-stores.md). This is where **materializers** come into play. A materializer dictates how a given artifact can be written to and retrieved from the artifact store and also contains all serialization and deserialization logic. Whenever you pass artifacts as outputs from one pipeline step to other steps as inputs, the corresponding materializer for the respective data type defines how this artifact is first serialized and written to the artifact store, and then deserialized and read in the next step. Read more about this [here](../../../how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md). However, there are instances where you might **not** want to materialize an artifact in a step, but rather use a reference to it instead. This is where skipping materialization comes in. {% hint style="warning" %} Skipping materialization might have unintended consequences for downstream tasks that rely on materialized artifacts. Only skip materialization if there is no other way to do what you want to do. {% endhint %} ## How to skip materialization While materializers should in most cases be used to control how artifacts are returned and consumed from pipeline steps, you might sometimes need to have a completely unmaterialized artifact in a step, e.g., if you need to know the exact path to where your artifact is stored. An unmaterialized artifact is a [`zenml.materializers.UnmaterializedArtifact`](https://sdkdocs.zenml.io/latest/core_code_docs/core-artifacts/#zenml.artifacts.unmaterialized_artifact). Among others, it has a property `uri` that points to the unique path in the artifact store where the artifact is persisted. One can use an unmaterialized artifact by specifying `UnmaterializedArtifact` as the type in the step: ```python from zenml.artifacts.unmaterialized_artifact import UnmaterializedArtifact from zenml import step @step def my_step(my_artifact: UnmaterializedArtifact): # rather than pd.DataFrame pass ``` ## Code Example The following shows an example of how unmaterialized artifacts can be used in the steps of a pipeline. The pipeline we define will look like this: ```shell s1 -> s3 s2 -> s4 ``` `s1` and `s2` produce identical artifacts, however `s3` consumes materialized artifacts while `s4` consumes unmaterialized artifacts. `s4` can now use the `dict_.uri` and `list_.uri` paths directly rather than their materialized counterparts. ```python from typing_extensions import Annotated # or `from typing import Annotated on Python 3.9+ from typing import Dict, List, Tuple from zenml.artifacts.unmaterialized_artifact import UnmaterializedArtifact from zenml import pipeline, step @step def step_1() -> Tuple[ Annotated[Dict[str, str], "dict_"], Annotated[List[str], "list_"], ]: return {"some": "data"}, [] @step def step_2() -> Tuple[ Annotated[Dict[str, str], "dict_"], Annotated[List[str], "list_"], ]: return {"some": "data"}, [] @step def step_3(dict_: Dict, list_: List) -> None: assert isinstance(dict_, dict) assert isinstance(list_, list) @step def step_4( dict_: UnmaterializedArtifact, list_: UnmaterializedArtifact, ) -> None: print(dict_.uri) print(list_.uri) @pipeline def example_pipeline(): step_3(*step_1()) step_4(*step_2()) example_pipeline() ``` You can see another example of using an `UnmaterializedArtifact` when triggering a [pipeline from another](../../trigger-pipelines/use-templates-python.md#advanced-usage-run-a-template-from-another-pipeline).
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/handle-data-artifacts/artifact-versioning.md ================ --- description: Understand how ZenML stores your data under-the-hood. --- # How ZenML stores data ZenML seamlessly integrates data versioning and lineage into its core functionality. When a pipeline is executed, each run generates automatically tracked and managed artifacts. One can easily view the entire lineage of how artifacts are created and interact with them. The dashboard is also a way to interact with the artifacts produced by different pipeline runs. ZenML's artifact management, caching, lineage tracking, and visualization capabilities can help gain valuable insights, streamline the experimentation process, and ensure the reproducibility and reliability of machine learning workflows. ## Artifact Creation and Caching Each time a ZenML pipeline runs, the system first checks if there have been any changes in the inputs, outputs, parameters, or configuration of the pipeline steps. Each step in a run gets a new directory in the artifact store: ![Artifact Stores Under the Hood](../../../.gitbook/assets/zenml_artifact_store_underthehood_1.png) Suppose a step is new or has been modified. In that case, ZenML creates a new directory structure in the [Artifact Store](../../../component-guide/artifact-stores/artifact-stores.md) with a unique ID and stores the data using the appropriate materializers in this directory. ![Artifact Stores Under the Hood](../../../.gitbook/assets/zenml_artifact_store_underthehood_2.png) On the other hand, if the step remains unchanged, ZenML intelligently decides whether to cache the step or not. By caching steps that have not been modified, ZenML can save [valuable time and computational resources](../../../user-guide/starter-guide/cache-previous-executions.md), allowing you to focus on experimenting with different configurations and improving your machine-learning models without the need to rerun unchanged parts of your pipeline. With ZenML, you can easily trace an artifact back to its origins and understand the exact sequence of executions that led to its creation, such as a trained model. This feature enables you to gain insights into the entire lineage of your artifacts, providing a clear understanding of how your data has been processed and transformed throughout your machine-learning pipelines. With ZenML, you can ensure the reproducibility of your results, and identify potential issues or bottlenecks in your pipelines. This level of transparency and traceability is essential for maintaining the reliability and trustworthiness of machine learning projects, especially when working in a team or across different environments. For more details on how to adjust the names or versions assigned to your artifacts, assign tags to them, or adjust other artifact properties, see the [documentation on artifact versioning and configuration](../../../user-guide/starter-guide/manage-artifacts.md). By tracking the lineage of artifacts across environments and stacks, ZenML enables ML engineers to reproduce results and understand the exact steps taken to create a model. This is crucial for ensuring the reliability and reproducibility of machine learning models, especially when working in a team or across different environments. ## Saving and Loading Artifacts with Materializers [Materializers](handle-custom-data-types.md) play a crucial role in ZenML's artifact management system. They are responsible for handling the serialization and deserialization of artifacts, ensuring that data is consistently stored and retrieved from the [artifact store](../../../component-guide/artifact-stores/artifact-stores.md). Each materializer stores data flowing through a pipeline in one or more files within a unique directory in the artifact store: ![Visualizing artifacts](../../../.gitbook/assets/zenml_artifact_store_underthehood_3.png) Materializers are designed to be extensible and customizable, allowing you to define your own serialization and deserialization logic for specific data types or storage systems. By default, ZenML provides built-in materializers for common data types and uses `cloudpickle` to pickle objects where there is no default materializer. If you want direct control over how objects are serialized, you can easily create custom materializers by extending the `BaseMaterializer` class and implementing the required methods for your specific use case. Read more about materializers [here](handle-custom-data-types.md). {% hint style="warning" %} ZenML provides a built-in [CloudpickleMaterializer](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-materializers/#zenml.materializers.cloudpickle\_materializer.CloudpickleMaterializer) that can handle any object by saving it with [cloudpickle](https://github.com/cloudpipe/cloudpickle). However, this is not production-ready because the resulting artifacts cannot be loaded when running with a different Python version. In such cases, you should consider building a [custom Materializer](handle-custom-data-types.md#custom-materializers) to save your objects in a more robust and efficient format. Moreover, using the `CloudpickleMaterializer` could allow users to upload of any kind of object. This could be exploited to upload a malicious file, which could execute arbitrary code on the vulnerable system. {% endhint %} When a pipeline runs, ZenML uses the appropriate materializers to save and load artifacts using the ZenML `fileio` system (built to work across multiple artifact stores). This not only simplifies the process of working with different data formats and storage systems but also enables artifact caching and lineage tracking. You can see an example of a default materializer (the `numpy` materializer) in action [here](https://github.com/zenml-io/zenml/blob/main/src/zenml/materializers/numpy\_materializer.py).
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/handle-data-artifacts/artifacts-naming.md ================ --- description: Understand how you can name your ZenML artifacts. --- # How Artifact Naming works in ZenML In ZenML pipelines, you often need to reuse the same step multiple times with different inputs, resulting in multiple artifacts. However, the default naming convention for artifacts can make it challenging to track and differentiate between these outputs, especially when they need to be used in subsequent pipelines. Below you can find a detailed exploration of how you might name your output artifacts dynamically or statically, depending on your needs. ZenML uses type annotations in function definitions to determine artifact names. Output artifacts with the same name are saved with incremented version numbers. ZenML provides flexible options for naming output artifacts, supporting both static and dynamic naming strategies: - Names can be generated dynamically at runtime - Support for string templates (standard and custom placeholders supported) - Compatible with single and multiple output scenarios - Annotations help define naming strategy without modifying core logic ## Naming Strategies ### Static Naming Static names are defined directly as string literals. ```python @step def static_single() -> Annotated[str, "static_output_name"]: return "null" ``` ### Dynamic Naming Dynamic names can be generated using: #### String Templates Using Standard Placeholders Use the following placeholders that ZenML will replace automatically: * `{date}` will resolve to the current date, e.g. `2024_11_18` * `{time}` will resolve to the current time, e.g. `11_07_09_326492` ```python @step def dynamic_single_string() -> Annotated[str, "name_{date}_{time}"]: return "null" ``` #### String Templates Using Custom Placeholders Use any placeholders that ZenML will replace for you, if they are provided into a step via `substitutions` parameter: ```python @step(substitutions={"custom_placeholder": "some_substitute"}) def dynamic_single_string() -> Annotated[str, "name_{custom_placeholder}_{time}"]: return "null" ``` Another option is to use `with_options` to dynamically redefine the placeholder, like this: ```python @step def extract_data(source: str) -> Annotated[str, "{stage}_dataset"]: ... return "my data" @pipeline def extraction_pipeline(): extract_data.with_options(substitutions={"stage": "train"})(source="s3://train") extract_data.with_options(substitutions={"stage": "test"})(source="s3://test") ``` {% hint style="info" %} The substitutions for the custom placeholders like `stage` can be set in: - `@pipeline` decorator, so they are effective for all steps in this pipeline - `pipeline.with_options` function, so they are effective for all steps in this pipeline run - `@step` decorator, so they are effective for this step (this overrides the pipeline settings) - `step.with_options` function, so they are effective for this step run (this overrides the pipeline settings) Standard substitutions always available and consistent in all steps of the pipeline are: - `{date}`: current date, e.g. `2024_11_27` - `{time}`: current time in UTC format, e.g. `11_07_09_326492` {% endhint %} ### Multiple Output Handling If you plan to return multiple artifacts from you ZenML step you can flexibly combine all naming options outlined above, like this: ```python @step def mixed_tuple() -> Tuple[ Annotated[str, "static_output_name"], Annotated[str, "name_{date}_{time}"], ]: return "static_namer", "str_namer" ``` ## Naming in cached runs If your ZenML step is running with enabled caching and cache was used the names of the outputs artifacts (both static and dynamic) will remain the same as in the original run. ```python from typing_extensions import Annotated from typing import Tuple from zenml import step, pipeline from zenml.models import PipelineRunResponse @step(substitutions={"custom_placeholder": "resolution"}) def demo() -> Tuple[ Annotated[int, "name_{date}_{time}"], Annotated[int, "name_{custom_placeholder}"], ]: return 42, 43 @pipeline def my_pipeline(): demo() if __name__ == "__main__": run_without_cache: PipelineRunResponse = my_pipeline.with_options( enable_cache=False )() run_with_cache: PipelineRunResponse = my_pipeline.with_options(enable_cache=True)() assert set(run_without_cache.steps["demo"].outputs.keys()) == set( run_with_cache.steps["demo"].outputs.keys() ) print(list(run_without_cache.steps["demo"].outputs.keys())) ``` These 2 runs will produce output like the one below: ``` Initiating a new run for the pipeline: my_pipeline. Caching is disabled by default for my_pipeline. Using user: default Using stack: default orchestrator: default artifact_store: default You can visualize your pipeline runs in the ZenML Dashboard. In order to try it locally, please run zenml login --local. Step demo has started. Step demo has finished in 0.038s. Pipeline run has finished in 0.064s. Initiating a new run for the pipeline: my_pipeline. Using user: default Using stack: default orchestrator: default artifact_store: default You can visualize your pipeline runs in the ZenML Dashboard. In order to try it locally, please run zenml login --local. Using cached version of step demo. All steps of the pipeline run were cached. ['name_2024_11_21_14_27_33_750134', 'name_resolution'] ```
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/handle-data-artifacts/delete-an-artifact.md ================ --- description: Learn how to delete artifacts. --- # Delete an artifact There is currently no way to delete an artifact directly, because it may lead to a broken state of the ZenML database (dangling references to pipeline runs that produce artifacts). However, it is possible to delete artifacts that are no longer referenced by any pipeline runs: ```shell zenml artifact prune ``` By default, this method deletes artifacts physically from the underlying [artifact store](../../../component-guide/artifact-stores/artifact-stores.md) AND also the entry in the database. You can control this behavior by using the `--only-artifact` and `--only-metadata` flags. You might find that some artifacts throw errors when you try to prune them, likely because they were stored locally and no longer exist. If you wish to continue pruning and to ignore these errors, please add the `--ignore-errors` flag. Warning messages will still be output to the terminal during this process.
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/handle-data-artifacts/get-arbitrary-artifacts-in-a-step.md ================ --- description: >- Not all artifacts need to come through the step interface from direct upstream steps. --- # Get arbitrary artifacts in a step As described in [the metadata guide](../../model-management-metrics/track-metrics-metadata/logging-metadata.md), the metadata can be fetched with the client, and this is how you would use it to fetch it within a step. This allows you to fetch artifacts from other upstream steps or even completely different pipelines. ```python from zenml.client import Client from zenml import step @step def my_step(): client = Client() # Directly fetch an artifact output = client.get_artifact_version("my_dataset", "my_version") output.run_metadata["accuracy"].value ``` This is one of the ways you can access artifacts that have already been created and stored in the artifact store. This can be useful when you want to use artifacts from other pipelines or steps that are not directly upstream. ## See Also - [Managing artifacts](../../../user-guide/starter-guide/manage-artifacts.md) - learn about the `ExternalArtifact` type and how to pass artifacts between steps.
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md ================ --- description: Using materializers to pass custom data types through steps. --- # Handle custom data types A ZenML pipeline is built in a data-centric way. The outputs and inputs of steps define how steps are connected and the order in which they are executed. Each step should be considered as its very own process that reads and writes its inputs and outputs from and to the [artifact store](../../../component-guide/artifact-stores/artifact-stores.md). This is where **materializers** come into play. A materializer dictates how a given artifact can be written to and retrieved from the artifact store and also contains all serialization and deserialization logic. Whenever you pass artifacts as outputs from one pipeline step to other steps as inputs, the corresponding materializer for the respective data type defines how this artifact is first serialized and written to the artifact store, and then deserialized and read in the next step. ## Built-In Materializers ZenML already includes built-in materializers for many common data types. These are always enabled and are used in the background without requiring any user interaction / activation:
MaterializerHandled Data TypesStorage Format
BuiltInMaterializerbool, float, int, str, None.json
BytesInMaterializerbytes.txt
BuiltInContainerMaterializerdict, list, set, tupleDirectory
NumpyMaterializernp.ndarray.npy
PandasMaterializerpd.DataFrame, pd.Series.csv (or .gzip if parquet is installed)
PydanticMaterializerpydantic.BaseModel.json
ServiceMaterializerzenml.services.service.BaseService.json
StructuredStringMaterializerzenml.types.CSVString, zenml.types.HTMLString, zenml.types.MarkdownString.csv / .html / .md (depending on type)
{% hint style="warning" %} ZenML provides a built-in [CloudpickleMaterializer](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-materializers/#zenml.materializers.cloudpickle\_materializer.CloudpickleMaterializer) that can handle any object by saving it with [cloudpickle](https://github.com/cloudpipe/cloudpickle). However, this is not production-ready because the resulting artifacts cannot be loaded when running with a different Python version. In such cases, you should consider building a [custom Materializer](handle-custom-data-types.md#custom-materializers) to save your objects in a more robust and efficient format. Moreover, using the `CloudpickleMaterializer` could allow users to upload of any kind of object. This could be exploited to upload a malicious file, which could execute arbitrary code on the vulnerable system. {% endhint %} ## Integration Materializers In addition to the built-in materializers, ZenML also provides several integration-specific materializers that can be activated by installing the respective [integration](../../../component-guide/README.md):
IntegrationMaterializerHandled Data TypesStorage Format
bentomlBentoMaterializerbentoml.Bento.bento
deepchecksDeepchecksResultMateriailzerdeepchecks.CheckResult, deepchecks.SuiteResult.json
evidentlyEvidentlyProfileMaterializerevidently.Profile.json
great_expectationsGreatExpectationsMaterializergreat_expectations.ExpectationSuite, great_expectations.CheckpointResult.json
huggingfaceHFDatasetMaterializerdatasets.Dataset, datasets.DatasetDictDirectory
huggingfaceHFPTModelMaterializertransformers.PreTrainedModelDirectory
huggingfaceHFTFModelMaterializertransformers.TFPreTrainedModelDirectory
huggingfaceHFTokenizerMaterializertransformers.PreTrainedTokenizerBaseDirectory
lightgbmLightGBMBoosterMaterializerlgbm.Booster.txt
lightgbmLightGBMDatasetMaterializerlgbm.Dataset.binary
neural_prophetNeuralProphetMaterializerNeuralProphet.pt
pillowPillowImageMaterializerPillow.Image.PNG
polarsPolarsMaterializerpl.DataFrame, pl.Series.parquet
pycaretPyCaretMaterializerAny sklearn, xgboost, lightgbm or catboost model.pkl
pytorchPyTorchDataLoaderMaterializertorch.Dataset, torch.DataLoader.pt
pytorchPyTorchModuleMaterializertorch.Module.pt
scipySparseMaterializerscipy.spmatrix.npz
sparkSparkDataFrameMaterializerpyspark.DataFrame.parquet
sparkSparkModelMaterializerpyspark.Transformerpyspark.Estimator
tensorflowKerasMaterializertf.keras.ModelDirectory
tensorflowTensorflowDatasetMaterializertf.DatasetDirectory
whylogsWhylogsMaterializerwhylogs.DatasetProfileView.pb
xgboostXgboostBoosterMaterializerxgb.Booster.json
xgboostXgboostDMatrixMaterializerxgb.DMatrix.binary
{% hint style="warning" %} If you are running pipelines with a Docker-based [orchestrator](../../../component-guide/orchestrators/orchestrators.md), you need to specify the corresponding integration as `required_integrations` in the `DockerSettings` of your pipeline in order to have the integration materializer available inside your Docker container. See the [pipeline configuration documentation](../../pipeline-development/use-configuration-files/runtime-configuration.md) for more information. {% endhint %} ## Custom materializers ### Configuring a step/pipeline to use a custom materializer #### Defining which step uses what materializer ZenML automatically detects if your materializer is imported in your source code and registers them for the corresponding data type (defined in `ASSOCIATED_TYPES`). Therefore, just having a custom materializer definition in your code is enough to enable the respective data type to be used in your pipelines. However, it is best practice to explicitly define which materializer to use for a specific step and not rely on the `ASSOCIATED_TYPES` to make that connection: ```python from zenml.materializers.base_materializer import BaseMaterializer from zenml.enums import ArtifactType class MyObj: ... class MyMaterializer(BaseMaterializer): """Materializer to read data to and from MyObj.""" ASSOCIATED_TYPES = (MyObj) ASSOCIATED_ARTIFACT_TYPE = ArtifactType.DATA # Read below to learn how to implement this materializer # You can define it at the decorator level @step(output_materializers=MyMaterializer) def my_first_step() -> MyObj: return 1 # No need to explicitly specify materializer here: # it is coupled with Artifact Version generated by # `my_first_step` already. def my_second_step(a: MyObj): print(a) # or you can use the `configure()` method of the step. E.g.: my_first_step.configure(output_materializers=MyMaterializer) ``` When there are multiple outputs, a dictionary of type `{: }` can be supplied to the decorator or the `.configure(...)` method: ```python from zenml.materializers.base_materializer import BaseMaterializer from zenml.enums import ArtifactType class MyObj1: ... class MyObj2: ... class MyMaterializer1(BaseMaterializer): """Materializer to read data to and from MyObj1.""" ASSOCIATED_TYPES = (MyObj1) ASSOCIATED_ARTIFACT_TYPE = ArtifactType.DATA class MyMaterializer2(BaseMaterializer): """Materializer to read data to and from MyObj2.""" ASSOCIATED_TYPES = (MyObj2) ASSOCIATED_ARTIFACT_TYPE = ArtifactType.DATA # This is where we connect the objects to the materializer @step(output_materializers={"1": MyMaterializer1, "2": MyMaterializer2}) def my_first_step() -> Tuple[Annotated[MyObj1, "1"], Annotated[MyObj2, "2"]]: return 1 ``` Also, as briefly outlined in the [configuration docs](../../pipeline-development/use-configuration-files/what-can-be-configured.md) section, which materializer to use for the output of what step can also be configured within YAML config files. For each output of your steps, you can define custom materializers to handle the loading and saving. You can configure them like this in the config: ```yaml ... steps: : ... outputs: : materializer_source: run.MyMaterializer ``` Check out [this page](../../../user-guide/starter-guide/manage-artifacts.md) for information on your step output names and how to customize them. #### Defining a materializer globally Sometimes, you would like to configure ZenML to use a custom materializer globally for all pipelines, and override the default materializers that come built-in with ZenML. A good example of this would be to build a materializer for a `pandas.DataFrame` to handle the reading and writing of that dataframe in a different way than the default mechanism. An easy way to do that is to use the internal materializer registry of ZenML and override its behavior: ```python # Entrypoint file where we run pipelines (i.e. run.py) from zenml.materializers.materializer_registry import materializer_registry # Create a new materializer class FastPandasMaterializer(BaseMaterializer): ... # Register the FastPandasMaterializer for pandas dataframes objects materializer_registry.register_and_overwrite_type(key=pd.DataFrame, type_=FastPandasMaterializer) # Run your pipelines: They will now all use the custom materializer ``` ### Developing a custom materializer Now that we know how to configure a pipeline to use a custom materializer, let us briefly discuss how materializers in general are implemented. #### Base implementation In the following, you can see the implementation of the abstract base class `BaseMaterializer`, which defines the interface of all materializers: ```python class BaseMaterializer(metaclass=BaseMaterializerMeta): """Base Materializer to realize artifact data.""" ASSOCIATED_ARTIFACT_TYPE = ArtifactType.BASE ASSOCIATED_TYPES = () def __init__( self, uri: str, artifact_store: Optional[BaseArtifactStore] = None ): """Initializes a materializer with the given URI. Args: uri: The URI where the artifact data will be stored. artifact_store: The artifact store used to store this artifact. """ self.uri = uri self._artifact_store = artifact_store def load(self, data_type: Type[Any]) -> Any: """Write logic here to load the data of an artifact. Args: data_type: The type of data that the artifact should be loaded as. Returns: The data of the artifact. """ # read from a location inside self.uri # # Example: # data_path = os.path.join(self.uri, "abc.json") # with self.artifact_store.open(filepath, "r") as fid: # return json.load(fid) ... def save(self, data: Any) -> None: """Write logic here to save the data of an artifact. Args: data: The data of the artifact to save. """ # write `data` into self.uri # # Example: # data_path = os.path.join(self.uri, "abc.json") # with self.artifact_store.open(filepath, "w") as fid: # json.dump(data,fid) ... def save_visualizations(self, data: Any) -> Dict[str, VisualizationType]: """Save visualizations of the given data. Args: data: The data of the artifact to visualize. Returns: A dictionary of visualization URIs and their types. """ # Optionally, define some visualizations for your artifact # # E.g.: # visualization_uri = os.path.join(self.uri, "visualization.html") # with self.artifact_store.open(visualization_uri, "w") as f: # f.write("data") # visualization_uri_2 = os.path.join(self.uri, "visualization.png") # data.save_as_png(visualization_uri_2) # return { # visualization_uri: ArtifactVisualizationType.HTML, # visualization_uri_2: ArtifactVisualizationType.IMAGE # } ... def extract_metadata(self, data: Any) -> Dict[str, "MetadataType"]: """Extract metadata from the given data. This metadata will be tracked and displayed alongside the artifact. Args: data: The data to extract metadata from. Returns: A dictionary of metadata. """ # Optionally, extract some metadata from `data` for ZenML to store. # # Example: # return { # "some_attribute_i_want_to_track": self.some_attribute, # "pi": 3.14, # } ... ``` #### Handled data types Each materializer has an `ASSOCIATED_TYPES` attribute that contains a list of data types that this materializer can handle. ZenML uses this information to call the right materializer at the right time. I.e., if a ZenML step returns a `pd.DataFrame`, ZenML will try to find any materializer that has `pd.DataFrame` in its `ASSOCIATED_TYPES`. List the data type of your custom object here to link the materializer to that data type. #### The type of the generated artifact Each materializer also has an `ASSOCIATED_ARTIFACT_TYPE` attribute, which defines what `zenml.enums.ArtifactType` is assigned to this data. In most cases, you should choose either `ArtifactType.DATA` or `ArtifactType.MODEL` here. If you are unsure, just use `ArtifactType.DATA`. The exact choice is not too important, as the artifact type is only used as a tag in some of ZenML's visualizations. #### Target location to store the artifact Each materializer has a `uri` attribute, which is automatically created by ZenML whenever you run a pipeline and points to the directory of a file system where the respective artifact is stored (some location in the artifact store). #### Storing and retrieving the artifact The `load()` and `save()` methods define the serialization and deserialization of artifacts. * `load()` defines how data is read from the artifact store and deserialized, * `save()` defines how data is serialized and saved to the artifact store. You will need to override these methods according to how you plan to serialize your objects. E.g., if you have custom PyTorch classes as `ASSOCIATED_TYPES`, then you might want to use `torch.save()` and `torch.load()` here. {% hint style="info" %} If you need a temporary directory in your custom materializer, it is best to use the helper method `get_temporary_directory(...)` on the materializer class in order to have the directory cleaned up correctly: ```python with self.get_temporary_directory(...) as temp_dir: ... ``` {% endhint %} #### (Optional) How to Visualize the Artifact Optionally, you can override the `save_visualizations()` method to automatically save visualizations for all artifacts saved by your materializer. These visualizations are then shown next to your artifacts in the dashboard: ![Evidently Artifact Visualization Example](../../../.gitbook/assets/artifact_visualization_dashboard.png) Currently, artifacts can be visualized either as CSV table, embedded HTML, image or Markdown. For more information, see [zenml.enums.VisualizationType](https://github.com/zenml-io/zenml/blob/main/src/zenml/enums.py). To create visualizations, you need to: 1. Compute the visualizations based on the artifact 2. Save all visualizations to paths inside `self.uri` 3. Return a dictionary mapping visualization paths to visualization types. As an example, check out the implementation of the [zenml.materializers.NumpyMaterializer](https://github.com/zenml-io/zenml/blob/main/src/zenml/materializers/numpy\_materializer.py) that use matplotlib to automatically save or plot certain arrays. Read more about visualizations [here](../visualize-artifacts/creating-custom-visualizations.md). #### (Optional) Which Metadata to Extract for the Artifact Optionally, you can override the `extract_metadata()` method to track custom metadata for all artifacts saved by your materializer. Anything you extract here will be displayed in the dashboard next to your artifacts. To extract metadata, define and return a dictionary of values you want to track. The only requirement is that all your values are built-in types ( like `str`, `int`, `list`, `dict`, ...) or among the special types defined in [zenml.metadata.metadata\_types](https://github.com/zenml-io/zenml/blob/main/src/zenml/metadata/metadata\_types.py) that are displayed in a dedicated way in the dashboard. See [zenml.metadata.metadata\_types.MetadataType](https://github.com/zenml-io/zenml/blob/main/src/zenml/metadata/metadata\_types.py) for more details. By default, this method will only extract the storage size of an artifact, but you can override it to track anything you wish. E.g., the [zenml.materializers.NumpyMaterializer](https://github.com/zenml-io/zenml/blob/main/src/zenml/materializers/numpy\_materializer.py) overrides this method to track the `shape`, `dtype`, and some statistical properties of each `np.ndarray` that it saves. {% hint style="info" %} If you would like to disable artifact visualization altogether, you can set `enable_artifact_visualization` at either pipeline or step level via `@pipeline(enable_artifact_visualization=False)` or `@step(enable_artifact_visualization=False)`. {% endhint %} #### (Optional) Which Metadata to Extract for the Artifact Optionally, you can override the `extract_metadata()` method to track custom metadata for all artifacts saved by your materializer. Anything you extract here will be displayed in the dashboard next to your artifacts. To extract metadata, define and return a dictionary of values you want to track. The only requirement is that all your values are built-in types ( like `str`, `int`, `list`, `dict`, ...) or among the special types defined in [src.zenml.metadata.metadata\_types](https://github.com/zenml-io/zenml/blob/main/src/zenml/metadata/metadata\_types.py) that are displayed in a dedicated way in the dashboard. See [src.zenml.metadata.metadata\_types.MetadataType](https://github.com/zenml-io/zenml/blob/main/src/zenml/metadata/metadata\_types.py) for more details. By default, this method will only extract the storage size of an artifact, but you can overwrite it to track anything you wish. E.g., the `zenml.materializers.NumpyMaterializer` overwrites this method to track the `shape`, `dtype`, and some statistical properties of each `np.ndarray` that it saves. {% hint style="info" %} If you would like to disable artifact metadata extraction altogether, you can set `enable_artifact_metadata` at either pipeline or step level via `@pipeline(enable_artifact_metadata=False)` or `@step(enable_artifact_metadata=False)`. {% endhint %} ## Skipping materialization You can learn more about skipping materialization [here](../complex-usecases/unmaterialized-artifacts.md). ## Interaction with custom artifact stores When creating a custom artifact store, you may encounter a situation where the default materializers do not function properly. Specifically, the `self.artifact_store.open` method used in these materializers may not be compatible with your custom store due to not being implemented properly. In this case, you can create a modified version of the failing materializer by copying it and modifying it to copy the artifact to a local path, then opening it from there. For example, consider the following implementation of a custom [PandasMaterializer](https://github.com/zenml-io/zenml/blob/main/src/zenml/materializers/pandas\_materializer.py) that works with a custom artifact store. In this implementation, we copy the artifact to a local path because we want to use the `pandas.read_csv` method to read it. If we were to use the `self.artifact_store.open` method instead, we would not need to make this copy. {% hint style="warning" %} It is worth noting that copying the artifact to a local path may not always be necessary and can potentially be a performance bottleneck. {% endhint %}
Pandas Materializer code example ```python import os from typing import Any, ClassVar, Dict, Optional, Tuple, Type, Union import pandas as pd from zenml.artifact_stores.base_artifact_store import BaseArtifactStore from zenml.enums import ArtifactType, VisualizationType from zenml.logger import get_logger from zenml.materializers.base_materializer import BaseMaterializer from zenml.metadata.metadata_types import DType, MetadataType logger = get_logger(__name__) PARQUET_FILENAME = "df.parquet.gzip" COMPRESSION_TYPE = "gzip" CSV_FILENAME = "df.csv" class PandasMaterializer(BaseMaterializer): """Materializer to read data to and from pandas.""" ASSOCIATED_TYPES: ClassVar[Tuple[Type[Any], ...]] = ( pd.DataFrame, pd.Series, ) ASSOCIATED_ARTIFACT_TYPE: ClassVar[ArtifactType] = ArtifactType.DATA def __init__( self, uri: str, artifact_store: Optional[BaseArtifactStore] = None ): """Define `self.data_path`. Args: uri: The URI where the artifact data is stored. artifact_store: The artifact store where the artifact data is stored. """ super().__init__(uri, artifact_store) try: import pyarrow # type: ignore # noqa self.pyarrow_exists = True except ImportError: self.pyarrow_exists = False logger.warning( "By default, the `PandasMaterializer` stores data as a " "`.csv` file. If you want to store data more efficiently, " "you can install `pyarrow` by running " "'`pip install pyarrow`'. This will allow `PandasMaterializer` " "to automatically store the data as a `.parquet` file instead." ) finally: self.parquet_path = os.path.join(self.uri, PARQUET_FILENAME) self.csv_path = os.path.join(self.uri, CSV_FILENAME) def load(self, data_type: Type[Any]) -> Union[pd.DataFrame, pd.Series]: """Reads `pd.DataFrame` or `pd.Series` from a `.parquet` or `.csv` file. Args: data_type: The type of the data to read. Raises: ImportError: If pyarrow or fastparquet is not installed. Returns: The pandas dataframe or series. """ if self.artifact_store.exists(self.parquet_path): if self.pyarrow_exists: with self.artifact_store.open( self.parquet_path, mode="rb" ) as f: df = pd.read_parquet(f) else: raise ImportError( "You have an old version of a `PandasMaterializer` " "data artifact stored in the artifact store " "as a `.parquet` file, which requires `pyarrow` " "for reading, You can install `pyarrow` by running " "'`pip install pyarrow fastparquet`'." ) else: with self.artifact_store.open(self.csv_path, mode="rb") as f: df = pd.read_csv(f, index_col=0, parse_dates=True) # validate the type of the data. def is_dataframe_or_series( df: Union[pd.DataFrame, pd.Series], ) -> Union[pd.DataFrame, pd.Series]: """Checks if the data is a `pd.DataFrame` or `pd.Series`. Args: df: The data to check. Returns: The data if it is a `pd.DataFrame` or `pd.Series`. """ if issubclass(data_type, pd.Series): # Taking the first column if it is a series as the assumption # is that there will only be one assert len(df.columns) == 1 df = df[df.columns[0]] return df else: return df return is_dataframe_or_series(df) def save(self, df: Union[pd.DataFrame, pd.Series]) -> None: """Writes a pandas dataframe or series to the specified filename. Args: df: The pandas dataframe or series to write. """ if isinstance(df, pd.Series): df = df.to_frame(name="series") if self.pyarrow_exists: with self.artifact_store.open(self.parquet_path, mode="wb") as f: df.to_parquet(f, compression=COMPRESSION_TYPE) else: with self.artifact_store.open(self.csv_path, mode="wb") as f: df.to_csv(f, index=True) ```
ZenML Scarf
## Code example Let's see how materialization works with a basic example. Let's say you have a custom class called `MyObject` that flows between two steps in a pipeline: ```python import logging from zenml import step, pipeline class MyObj: def __init__(self, name: str): self.name = name @step def my_first_step() -> MyObj: """Step that returns an object of type MyObj.""" return MyObj("my_object") @step def my_second_step(my_obj: MyObj) -> None: """Step that logs the input object and returns nothing.""" logging.info( f"The following object was passed to this step: `{my_obj.name}`" ) @pipeline def first_pipeline(): output_1 = my_first_step() my_second_step(output_1) first_pipeline() ``` Running the above without a custom materializer will work but print the following warning: `No materializer is registered for type MyObj, so the default Pickle materializer was used. Pickle is not production ready and should only be used for prototyping as the artifacts cannot be loaded when running with a different Python version. Please consider implementing a custom materializer for type MyObj` To get rid of this warning and make our pipeline more robust, we will subclass the `BaseMaterializer` class, listing `MyObj` in `ASSOCIATED_TYPES`, and overwriting `load()` and `save()`: ```python import os from typing import Type from zenml.enums import ArtifactType from zenml.materializers.base_materializer import BaseMaterializer class MyMaterializer(BaseMaterializer): ASSOCIATED_TYPES = (MyObj,) ASSOCIATED_ARTIFACT_TYPE = ArtifactType.DATA def load(self, data_type: Type[MyObj]) -> MyObj: """Read from artifact store.""" with self.artifact_store.open(os.path.join(self.uri, 'data.txt'), 'r') as f: name = f.read() return MyObj(name=name) def save(self, my_obj: MyObj) -> None: """Write to artifact store.""" with self.artifact_store.open(os.path.join(self.uri, 'data.txt'), 'w') as f: f.write(my_obj.name) ``` {% hint style="info" %} Pro-tip: Use the `self.artifact_store` property to ensure your materialization logic works across artifact stores (local and remote like S3 buckets). {% endhint %} Now, ZenML can use this materializer to handle the outputs and inputs of your customs object. Edit the pipeline as follows to see this in action: ```python my_first_step.configure(output_materializers=MyMaterializer) first_pipeline() ``` {% hint style="info" %} Due to the typing of the inputs and outputs and the `ASSOCIATED_TYPES` attribute of the materializer, you won't necessarily have to add `.configure(output_materializers=MyMaterializer)` to the step. It should automatically be detected. It doesn't hurt to be explicit though. {% endhint %} This will now work as expected and yield the following output: ```shell Creating run for pipeline: `first_pipeline` Cache enabled for pipeline `first_pipeline` Using stack `default` to run pipeline `first_pipeline`... Step `my_first_step` has started. Step `my_first_step` has finished in 0.081s. Step `my_second_step` has started. The following object was passed to this step: `my_object` Step `my_second_step` has finished in 0.048s. Pipeline run `first_pipeline-22_Apr_22-10_58_51_135729` has finished in 0.153s. ```
Code Example for Materializing Custom Objects ```python import logging import os from typing import Type from zenml import step, pipeline from zenml.enums import ArtifactType from zenml.materializers.base_materializer import BaseMaterializer class MyObj: def __init__(self, name: str): self.name = name class MyMaterializer(BaseMaterializer): ASSOCIATED_TYPES = (MyObj,) ASSOCIATED_ARTIFACT_TYPE = ArtifactType.DATA def load(self, data_type: Type[MyObj]) -> MyObj: """Read from artifact store.""" with self.artifact_store.open(os.path.join(self.uri, 'data.txt'), 'r') as f: name = f.read() return MyObj(name=name) def save(self, my_obj: MyObj) -> None: """Write to artifact store.""" with self.artifact_store.open(os.path.join(self.uri, 'data.txt'), 'w') as f: f.write(my_obj.name) @step def my_first_step() -> MyObj: """Step that returns an object of type MyObj.""" return MyObj("my_object") my_first_step.configure(output_materializers=MyMaterializer) @step def my_second_step(my_obj: MyObj) -> None: """Step that log the input object and returns nothing.""" logging.info( f"The following object was passed to this step: `{my_obj.name}`" ) @pipeline def first_pipeline(): output_1 = my_first_step() my_second_step(output_1) if __name__ == "__main__": first_pipeline() ```
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/handle-data-artifacts/load-artifacts-into-memory.md ================ # Load artifacts into memory Often ZenML pipeline steps consume artifacts produced by one another directly in the pipeline code, but there are scenarios where you need to pull external data into your steps. Such external data could be artifacts produced by non-ZenML codes. For those cases, it is advised to use [ExternalArtifact](../../../user-guide/starter-guide/manage-artifacts.md#consuming-external-artifacts-within-a-pipeline), but what if we plan to exchange data created with other ZenML pipelines? ZenML pipelines are first compiled and only executed at some later point. During the compilation phase, all function calls are executed, and this data is fixed as step input parameters. Given all this, the late materialization of dynamic objects, like data artifacts, is crucial. Without late materialization, it would not be possible to pass not-yet-existing artifacts as step inputs, or their metadata, which is often the case in a multi-pipeline setting. We identify two major use cases for exchanging artifacts between pipelines: * You semantically group your data products using ZenML Models * You prefer to use [ZenML Client](../../../reference/python-client.md#client-methods) to bring all the pieces together {% hint style="warning" %} We recommend using models to group and access artifacts across pipelines. Find out how to load an artifact from a ZenML Model [here](../../model-management-metrics/model-control-plane/load-artifacts-from-model.md). {% endhint %} ## Use client methods to exchange artifacts If you don't yet use the Model Control Plane, you can still exchange data between pipelines with late materialization. Let's rework the `do_predictions` pipeline code as follows: ```python from typing import Annotated from zenml import step, pipeline from zenml.client import Client import pandas as pd from sklearn.base import ClassifierMixin @step def predict( model1: ClassifierMixin, model2: ClassifierMixin, model1_metric: float, model2_metric: float, data: pd.DataFrame, ) -> Annotated[pd.Series, "predictions"]: # compare which model performs better on the fly if model1_metric < model2_metric: predictions = pd.Series(model1.predict(data)) else: predictions = pd.Series(model2.predict(data)) return predictions @step def load_data() -> pd.DataFrame: # load inference data ... @pipeline def do_predictions(): # get specific artifact version model_42 = Client().get_artifact_version("trained_model", version="42") metric_42 = model_42.run_metadata["MSE"].value # get latest artifact version model_latest = Client().get_artifact_version("trained_model") metric_latest = model_latest.run_metadata["MSE"].value inference_data = load_data() predict( model1=model_42, model2=model_latest, model1_metric=metric_42, model2_metric=metric_latest, data=inference_data, ) if __name__ == "__main__": do_predictions() ``` Here, we enriched the `predict` step logic with a metric comparison by MSE metric, so predictions are done on the best possible model. We also added a `load_data` step to load the inference data. As before, calls like `Client().get_artifact_version("trained_model", version="42")` or `model_latest.run_metadata["MSE"].value` are not evaluating the actual objects behind them at pipeline compilation time. Rather, they do so only at the point of step execution. By doing so, we ensure that the latest version is actually the latest at the moment and not just the latest at the point of pipeline compilation.
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/handle-data-artifacts/README.md ================ --- icon: box-archive description: >- Step outputs in ZenML are stored in the artifact store. This enables caching, lineage and auditability. Using type annotations helps with transparency, passing data between steps, and serializing/deserializing the data. --- # Handle Data/Artifacts For best results, use type annotations for your outputs. This is good coding practice for transparency, helps ZenML handle passing data between steps, and also enables ZenML to serialize and deserialize (referred to as 'materialize' in ZenML) the data. ```python @step def load_data(parameter: int) -> Dict[str, Any]: # do something with the parameter here training_data = [[1, 2], [3, 4], [5, 6]] labels = [0, 1, 0] return {'features': training_data, 'labels': labels} @step def train_model(data: Dict[str, Any]) -> None: total_features = sum(map(sum, data['features'])) total_labels = sum(data['labels']) # Train some model here print(f"Trained model using {len(data['features'])} data points. " f"Feature sum is {total_features}, label sum is {total_labels}") @pipeline def simple_ml_pipeline(parameter: int): dataset = load_data(parameter=parameter) # Get the output train_model(dataset) # Pipe the previous step output into the downstream step ``` In this code, we define two steps: `load_data` and `train_model`. The `load_data` step takes an integer parameter and returns a dictionary containing training data and labels. The `train_model` step receives the dictionary from `load_data`, extracts the features and labels, and trains a model (not shown here). Finally, we define a pipeline `simple_ml_pipeline` that chains the `load_data` and `train_model` steps together. The output from `load_data` is passed as input to `train_model`, demonstrating how data flows between steps in a ZenML pipeline.
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/handle-data-artifacts/return-multiple-outputs-from-a-step.md ================ --- description: Use Annotated to return multiple outputs from a step and name them for easy retrieval and dashboard display. --- # Return multiple outputs from a step You can use the `Annotated` type to return multiple outputs from a step and give each output a name. Naming your step outputs will help you retrieve the specific artifact later and also improves the readability of your pipeline's dashboard. ```python from typing import Annotated, Tuple import pandas as pd from zenml import step @step def clean_data( data: pd.DataFrame, ) -> Tuple[ Annotated[pd.DataFrame, "x_train"], Annotated[pd.DataFrame, "x_test"], Annotated[pd.Series, "y_train"], Annotated[pd.Series, "y_test"], ]: from sklearn.model_selection import train_test_split x = data.drop("target", axis=1) y = data["target"] x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42) return x_train, x_test, y_train, y_test ``` In this code, the `clean_data` step takes a pandas DataFrame as input and returns a tuple of four elements: `x_train`, `x_test`, `y_train`, and `y_test`. Each element in the tuple is annotated with a specific name using the `Annotated` type. Inside the step, we split the input data into features (`x`) and target (`y`), and then use `train_test_split` from scikit-learn to split the data into training and testing sets. The resulting DataFrames and Series are returned as a tuple, with each element annotated with its respective name. By using `Annotated`, we can easily identify and retrieve specific artifacts later in the pipeline. Additionally, the names will be displayed on the pipeline's dashboard, making it more readable and understandable.
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/handle-data-artifacts/tagging.md ================ --- description: Use tags to organize tags in ZenML. --- # Organizing data with tags Organizing and categorizing your machine learning artifacts and models can streamline your workflow and enhance discoverability. ZenML enables the use of tags as a flexible tool to classify and filter your ML assets. In this guide, we'll demonstrate how to assign tags to both artifacts and models within the ZenML ecosystem. ![Tags are visible in the ZenML Dashboard](../../../.gitbook/assets/tags-in-dashboard.png) ## Assigning tags to artifacts If you want to tag the artifact versions of a step or pipeline that is executed repeatedly, you can use the `tags` property of `ArtifactConfig` to assign an arbitrary number of tags to the created artifacts: {% tabs %} {% tab title="Python SDK" %} ```python from zenml import step, ArtifactConfig @step def training_data_loader() -> ( Annotated[pd.DataFrame, ArtifactConfig(tags=["sklearn", "pre-training"])] ): ... ``` {% endtab %} {% tab title="CLI" %} You can use the `zenml artifacts` CLI to add tags: ```shell # Tag the artifact zenml artifacts update iris_dataset -t sklearn # Tag the artifact version zenml artifacts versions update iris_dataset raw_2023 -t sklearn ``` {% endtab %} {% endtabs %} This will assign tags `sklearn` and `pre-training` to all artifacts created by this step, which can later be used to filter and organize these artifacts. Note that [ZenML Pro](https://zenml.io/pro) users can tag artifacts directly in the cloud dashboard. ## Assigning tags to models Just like artifacts, you can also tag your models to organize them semantically. Here's how to use tags with models in the ZenML Python SDK and CLI (or in the [ZenML Pro Dashboard directly](https://zenml.io/pro)). When creating a model version using the `Model` object, you can specify tags as key-value pairs that will be attached to the model version upon creation. {% hint style="warning" %} During pipeline run a model can be also implicitly created (if not exists), in such cases it will not get the `tags` from the `Model` class. You can manipulate the model tags using SDK (see below) or the ZenML Pro UI. {% endhint %} ```python from zenml.models import Model # Define tags to be added to the model version tags = ["experiment", "v1", "classification-task"] # Create a model version with tags model = Model( name="iris_classifier", version="1.0.0", tags=tags, ) # Use this tagged model in your steps and pipelines as needed @pipeline(model=model) def my_pipeline(...): ... ``` You can also assign tags when creating or updating models with the Python SDK: ```python from zenml.models import Model from zenml.client import Client # Create or register a new model with tags Client().create_model( name="iris_logistic_regression", tags=["classification", "iris-dataset"], ) # Create or register a new model version also with tags Client().create_model_version( model_name_or_id="iris_logistic_regression", name="2", tags=["version-1", "experiment-42"], ) ``` To add tags to existing models and their versions using the ZenML CLI, you can use the following commands: ```shell # Tag an existing model zenml model update iris_logistic_regression --tag "classification" # Tag a specific model version zenml model version update iris_logistic_regression 2 --tag "experiment3" ```
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/visualize-artifacts/creating-custom-visualizations.md ================ --- description: Creating your own visualizations. --- # Creating Custom Visualizations It is simple to associate a custom visualization with an artifact in ZenML, if the visualization is one of the supported visualization types. Currently, the following visualization types are supported: * **HTML:** Embedded HTML visualizations such as data validation reports, * **Image:** Visualizations of image data such as Pillow images (e.g. `PIL.Image`) or certain numeric numpy arrays, * **CSV:** Tables, such as the pandas DataFrame `.describe()` output, * **Markdown:** Markdown strings or pages. * **JSON:** JSON strings or objects. There are three ways how you can add custom visualizations to the dashboard: * If you are already handling HTML, Markdown, CSV or JSON data in one of your steps, you can have them visualized in just a few lines of code by casting them to a [special class](#visualization-via-special-return-types) inside your step. * If you want to automatically extract visualizations for all artifacts of a certain data type, you can define type-specific visualization logic by [building a custom materializer](#visualization-via-materializers). * If you want to create any other custom visualizations, you can [create a custom return type class with corresponding materializer](#how-to-think-about-creating-a-custom-visualization) and build and return this custom return type from one of your steps. ## Visualization via Special Return Types If you already have HTML, Markdown, CSV or JSON data available as a string inside your step, you can simply cast them to one of the following types and return them from your step: * `zenml.types.HTMLString` for strings in HTML format, e.g., `"

Header

Some text"`, * `zenml.types.MarkdownString` for strings in Markdown format, e.g., `"# Header\nSome text"`, * `zenml.types.CSVString` for strings in CSV format, e.g., `"a,b,c\n1,2,3"`. * `zenml.types.JSONString` for strings in JSON format, e.g., `{"key": "value"}`. ### Example: ```python from zenml.types import CSVString @step def my_step() -> CSVString: some_csv = "a,b,c\n1,2,3" return CSVString(some_csv) ``` This would create the following visualization in the dashboard: ![CSV Visualization Example](../../.gitbook/assets/artifact_visualization_csv.png) Another example is visualizing a matplotlib plot by embedding the image in an HTML string: ```python import matplotlib.pyplot as plt import base64 import io from zenml.types import HTMLString from zenml import step, pipeline @step def create_matplotlib_visualization() -> HTMLString: """Creates a matplotlib visualization and returns it as embedded HTML.""" # Create plot fig, ax = plt.subplots() ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) ax.set_title('Sample Plot') # Convert plot to base64 string buf = io.BytesIO() fig.savefig(buf, format='png', bbox_inches='tight', dpi=300) plt.close(fig) # Clean up image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8') # Create HTML with embedded image html = f'''
''' return HTMLString(html) @pipeline def visualization_pipeline(): create_matplotlib_visualization() if __name__ == "__main__": visualization_pipeline() ``` ## Visualization via Materializers If you want to automatically extract visualizations for all artifacts of a certain data type, you can do so by overriding the `save_visualizations()` method of the corresponding [materializer](../../data-artifact-management/handle-data-artifacts/handle-custom-data-types.md#custom-materializers). Let's look at an example of how to visualize matplotlib figures in your ZenML dashboard: ### Example: Matplotlib Figure Visualization **1. Custom Class** First, we create a custom class to hold our matplotlib figure: ```python from pydantic import BaseModel class MatplotlibVisualization(BaseModel): """Custom class to hold matplotlib figures.""" figure: Any # This will hold the matplotlib figure ``` **2. Materializer** Next, we create a [custom materializer](../../data-artifact-management/handle-data-artifacts/handle-custom-data-types.md#custom-materializers) that handles this class and implements the visualization logic: ```python class MatplotlibMaterializer(BaseMaterializer): """Materializer that handles matplotlib figures.""" ASSOCIATED_TYPES = (MatplotlibVisualization,) def save_visualizations( self, data: MatplotlibVisualization ) -> Dict[str, VisualizationType]: """Create and save visualizations for the matplotlib figure.""" visualization_path = os.path.join(self.uri, "visualization.png") with fileio.open(visualization_path, 'wb') as f: data.figure.savefig(f, format='png', bbox_inches='tight') return {visualization_path: VisualizationType.IMAGE} ``` **3. Step** Finally, we create a step that returns our custom type: ```python @step def create_matplotlib_visualization() -> MatplotlibVisualization: """Creates a matplotlib visualization.""" fig, ax = plt.subplots() ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) ax.set_title('Sample Plot') return MatplotlibVisualization(figure=fig) ``` {% hint style="info" %} When you use this step in your pipeline: 1. The step creates and returns a `MatplotlibVisualization` 2. ZenML finds the `MatplotlibMaterializer` and calls `save_visualizations()` 3. The figure is saved as a PNG file in your artifact store 4. The dashboard loads and displays this PNG when you view the artifact {% endhint %} For another example, see our [Hugging Face datasets materializer](https://github.com/zenml-io/zenml/blob/main/src/zenml/integrations/huggingface/materializers/huggingface_datasets_materializer.py) which visualizes datasets by embedding their preview viewer.
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/visualize-artifacts/disabling-visualizations.md ================ --- description: Disabling visualizations. --- # Disabling Visualizations If you would like to disable artifact visualization altogether, you can set `enable_artifact_visualization` at either pipeline or step level: ```python @step(enable_artifact_visualization=False) def my_step(): ... @pipeline(enable_artifact_visualization=False) def my_pipeline(): ... ```
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/visualize-artifacts/README.md ================ --- icon: chart-scatter description: Configuring ZenML to display data visualizations in the dashboard. --- # Visualize artifacts It is easy to associate visualizations of data and artifacts in ZenML: ![ZenML Artifact Visualizations](../../../.gitbook/assets/artifact_visualization_dashboard.png)
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/visualize-artifacts/types-of-visualizations.md ================ --- description: Types of visualizations in ZenML. --- # Types of visualizations ZenML automatically saves visualizations of many common data types and allows you to view these visualizations in the ZenML dashboard: ![ZenML Artifact Visualizations](../../../.gitbook/assets/artifact_visualization_dashboard.png) Alternatively, any of these visualizations can also be displayed in Jupyter notebooks using the `artifact.visualize()` method: ![output.visualize() Output](../../../.gitbook/assets/artifact_visualization_evidently.png) Some examples of default visualizations are: - A statistical representation of a [Pandas](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html) Dataframe represented as a png image. - Drift detection reports by [Evidently](../../../component-guide/data-validators/evidently.md), [Great Expectations](../../../component-guide/data-validators/great-expectations.md), and [whylogs](../../../component-guide/data-validators/whylogs.md). - A [Hugging Face](https://zenml.io/integrations/huggingface) datasets viewer embedded as a HTML iframe. ![output.visualize() output for the Hugging Face datasets viewer](../../../.gitbook/assets/artifact_visualization_huggingface.gif)
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/visualize-artifacts/visualizations-in-dashboard.md ================ --- description: Displaying visualizations in the dashboard. --- # Giving the ZenML Server Access to Visualizations In order for the visualizations to show up on the dashboard, the following must be true: ## Configuring a Service Connector Visualizations are usually stored alongside the artifact, in the [artifact store](../../../component-guide/artifact-stores/artifact-stores.md). Therefore, if a user would like to see the visualization displayed on the ZenML dashboard, they must give access to the server to connect to the artifact store. The [service connector](../../infrastructure-deployment/auth-management/README.md) documentation goes deeper into the concept of service connectors and how they can be configured to give the server permission to access the artifact store. For a concrete example, see the [AWS S3](../../../component-guide/artifact-stores/s3.md) artifact store documentation. {% hint style="info" %} When using the default/local artifact store with a deployed ZenML, the server naturally does not have access to your local files. In this case, the visualizations are also not displayed on the dashboard. Please use a service connector enabled and remote artifact store alongside a deployed ZenML to view visualizations. {% endhint %} ## Configuring Artifact Stores If all visualizations of a certain pipeline run are not showing up in the dashboard, it might be that your ZenML server does not have the required dependencies or permissions to access that artifact store. See the [custom artifact store docs page](../../../component-guide/artifact-stores/custom.md#enabling-artifact-visualizations-with-custom-artifact-stores) for more information.
ZenML Scarf
================ File: docs/book/how-to/data-artifact-management/README.md ================ --- icon: chart-network --- # Data and Artifact Management This section covers all aspects of managing data and artifacts in ZenML. ================ File: docs/book/how-to/infrastructure-deployment/auth-management/aws-service-connector.md ================ --- description: >- Configuring AWS Service Connectors to connect ZenML to AWS resources like S3 buckets, EKS Kubernetes clusters and ECR container registries. --- # AWS Service Connector The ZenML AWS Service Connector facilitates the authentication and access to managed AWS services and resources. These encompass a range of resources, including S3 buckets, ECR container repositories, and EKS clusters. The connector provides support for various authentication methods, including explicit long-lived AWS secret keys, IAM roles, short-lived STS tokens, and implicit authentication. To ensure heightened security measures, this connector also enables [the generation of temporary STS security tokens that are scoped down to the minimum permissions necessary](best-security-practices.md#generating-temporary-and-down-scoped-credentials) for accessing the intended resource. Furthermore, it includes [automatic configuration and detection of credentials locally configured through the AWS CLI](service-connectors-guide.md#auto-configuration). This connector serves as a general means of accessing any AWS service by issuing pre-authenticated boto3 sessions. Additionally, the connector can handle specialized authentication for S3, Docker, and Kubernetes Python clients. It also allows for the configuration of local Docker and Kubernetes CLIs. ```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 │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` {% hint style="info" %} This service connector will not be able to work if [Multi-Factor Authentication (MFA)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id\_credentials\_mfa\_enable\_cliapi.html) is enabled on the role used by the AWS CLI. When MFA is enabled, the AWS CLI generates temporary credentials that are valid for a limited time. These temporary credentials cannot be used by the ZenML AWS Service Connector, as it requires long-lived credentials to authenticate and access AWS resources. To use the AWS Service Connector with ZenML, you will need to use a different AWS CLI profile that does not have MFA enabled. You can do this by setting the `AWS_PROFILE` environment variable to the name of the profile you want to use before running the ZenML CLI commands. {% endhint %} ## Prerequisites The AWS Service Connector is part of the AWS ZenML integration. You can either install the entire integration or use a PyPI extra to install it independently of the integration: * `pip install "zenml[connectors-aws]"` installs only prerequisites for the AWS Service Connector Type * `zenml integration install aws` installs the entire AWS ZenML integration It is not required to [install and set up the AWS CLI on your local machine](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) to use the AWS Service Connector to link Stack Components to AWS resources and services. However, it is recommended to do so if you are looking for a quick setup that includes using the auto-configuration Service Connector features. {% hint style="info" %} The auto-configuration examples in this page rely on the AWS CLI being installed and already configured with valid credentials of one type or another. If you want to avoid installing the AWS CLI, we recommend using the interactive mode of the ZenML CLI to register Service Connectors: ``` zenml service-connector register -i --type aws ``` {% endhint %} ## Resource Types ### Generic AWS resource This resource type allows consumers to use the AWS Service Connector to connect to any AWS service or resource. When used by connector clients, they are provided a generic Python boto3 session instance pre-configured with AWS credentials. This session can then be used to create boto3 clients for any particular AWS service. This generic AWS resource type is meant to be used with Stack Components that are not represented by other, more specific resource types, like S3 buckets, Kubernetes clusters, or Docker registries. It should be accompanied by a matching set of AWS permissions that allow access to the set of remote resources required by the client(s). The resource name represents the AWS region that the connector is authorized to access. ### S3 bucket Allows users to connect to S3 buckets. When used by connector consumers, they are provided a pre-configured boto3 S3 client instance. The configured credentials must have at least the following [AWS IAM permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access\_policies.html) associated with [the ARNs of S3 buckets ](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-arn-format.html)that the connector will be allowed to access (e.g. `arn:aws:s3:::*` and `arn:aws:s3:::*/*` represent all the available S3 buckets). * `s3:ListBucket` * `s3:GetObject` * `s3:PutObject` * `s3:DeleteObject` * `s3:ListAllMyBuckets` * `s3:GetBucketVersioning` * `s3:ListBucketVersions` * `s3:DeleteObjectVersion` {% hint style="info" %} If you are using the [AWS IAM role](aws-service-connector.md#aws-iam-role), [Session Token](aws-service-connector.md#aws-session-token), or [Federation Token](aws-service-connector.md#aws-federation-token) authentication methods, you don't have to worry too much about restricting the permissions of the AWS credentials that you use to access the AWS cloud resources. These authentication methods already support [automatically generating temporary tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials) with permissions down-scoped to the minimum required to access the target resource. {% endhint %} If set, the resource name must identify an S3 bucket using one of the following formats: * S3 bucket URI (canonical resource name): `s3://{bucket-name}` * S3 bucket ARN: `arn:aws:s3:::{bucket-name}` * S3 bucket name: `{bucket-name}` ### EKS Kubernetes cluster Allows users to access an EKS cluster as a standard Kubernetes cluster resource. When used by Stack Components, they are provided a pre-authenticated Python Kubernetes client instance. The configured credentials must have at least the following [AWS IAM permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access\_policies.html) associated with the [ARNs of EKS clusters](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html) that the connector will be allowed to access (e.g. `arn:aws:eks:{region_id}:{project_id}:cluster/*` represents all the EKS clusters available in the target AWS region). * `eks:ListClusters` * `eks:DescribeCluster` {% hint style="info" %} If you are using the [AWS IAM role](aws-service-connector.md#aws-iam-role), [Session Token](aws-service-connector.md#aws-session-token) or [Federation Token](aws-service-connector.md#aws-federation-token) authentication methods, you don't have to worry too much about restricting the permissions of the AWS credentials that you use to access the AWS cloud resources. These authentication methods already support [automatically generating temporary tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials) with permissions down-scoped to the minimum required to access the target resource. {% endhint %} In addition to the above permissions, if the credentials are not associated with the same IAM user or role that created the EKS cluster, the IAM principal must be manually added to the EKS cluster's `aws-auth` ConfigMap, otherwise the Kubernetes client will not be allowed to access the cluster's resources. This makes it more challenging to use [the AWS Implicit](aws-service-connector.md#implicit-authentication) and [AWS Federation Token](aws-service-connector.md#aws-federation-token) authentication methods for this resource. For more information, [see this documentation](https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html). If set, the resource name must identify an EKS cluster using one of the following formats: * EKS cluster name (canonical resource name): `{cluster-name}` * EKS cluster ARN: `arn:aws:eks:{region}:{account-id}:cluster/{cluster-name}` EKS cluster names are region scoped. The connector can only be used to access EKS clusters in the AWS region that it is configured to use. ### ECR container registry Allows Stack Components to access one or more ECR repositories as a standard Docker registry resource. When used by Stack Components, they are provided a pre-authenticated python-docker client instance. The configured credentials must have at least the following [AWS IAM permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access\_policies.html) associated with the [ARNs of one or more ECR repositories](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference-arns.html) that the connector will be allowed to access (e.g. `arn:aws:ecr:{region}:{account}:repository/*` represents all the ECR repositories available in the target AWS region). * `ecr:DescribeRegistry` * `ecr:DescribeRepositories` * `ecr:ListRepositories` * `ecr:BatchGetImage` * `ecr:DescribeImages` * `ecr:BatchCheckLayerAvailability` * `ecr:GetDownloadUrlForLayer` * `ecr:InitiateLayerUpload` * `ecr:UploadLayerPart` * `ecr:CompleteLayerUpload` * `ecr:PutImage` * `ecr:GetAuthorizationToken` {% hint style="info" %} If you are using the [AWS IAM role](aws-service-connector.md#aws-iam-role), [Session Token](aws-service-connector.md#aws-session-token), or [Federation Token](aws-service-connector.md#aws-federation-token) authentication methods, you don't have to worry too much about restricting the permissions of the AWS credentials that you use to access the AWS cloud resources. These authentication methods already support [automatically generating temporary tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials) with permissions down-scoped to the minimum required to access the target resource. {% endhint %} This resource type is not scoped to a single ECR repository. Instead, a connector configured with this resource type will grant access to all the ECR repositories that the credentials are allowed to access under the configured AWS region (i.e. all repositories under the Docker registry URL `https://{account-id}.dkr.ecr.{region}.amazonaws.com`). The resource name associated with this resource type uniquely identifies an ECR registry using one of the following formats (the repository name is ignored, only the registry URL/ARN is used): * ECR repository URI (canonical resource name): `[https://]{account}.dkr.ecr.{region}.amazonaws.com[/{repository-name}]` * ECR repository ARN : `arn:aws:ecr:{region}:{account-id}:repository[/{repository-name}]` ECR repository names are region scoped. The connector can only be used to access ECR repositories in the AWS region that it is configured to use. ## Authentication Methods ### Implicit authentication [Implicit authentication](best-security-practices.md#implicit-authentication) to AWS services using environment variables, local configuration files or IAM roles. {% hint style="warning" %} This method may constitute a security risk, because it can give users access to the same cloud resources and services that the ZenML Server itself is configured to access. For this reason, all implicit authentication methods are disabled by default and need to be explicitly enabled by setting the `ZENML_ENABLE_IMPLICIT_AUTH_METHODS` environment variable or the helm chart `enableImplicitAuthMethods` configuration option to `true` in the ZenML deployment. {% endhint %} This authentication method doesn't require any credentials to be explicitly configured. It automatically discovers and uses credentials from one of the following sources: * environment variables (AWS\_ACCESS\_KEY\_ID, AWS\_SECRET\_ACCESS\_KEY, AWS\_SESSION\_TOKEN, AWS\_DEFAULT\_REGION) * local configuration files [set up through the AWS CLI ](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)(\~/aws/credentials, \~/.aws/config) * IAM roles for Amazon EC2, ECS, EKS, Lambda, etc. Only works when running the ZenML server on an AWS resource with an IAM role attached to it. This is the quickest and easiest way to authenticate to AWS services. However, the results depend on how ZenML is deployed and the environment where it is used and is thus not fully reproducible: * when used with the default local ZenML deployment or a local ZenML server, the credentials are the same as those used by the AWS CLI or extracted from local environment variables * when connected to a ZenML server, this method only works if the ZenML server is deployed in AWS and will use the IAM role attached to the AWS resource where the ZenML server is running (e.g. an EKS cluster). The IAM role permissions may need to be adjusted to allow listing and accessing/describing the AWS resources that the connector is configured to access. An IAM role may optionally be specified to be assumed by the connector on top of the implicit credentials. This is only possible when the implicit credentials have permissions to assume the target IAM role. Configuring an IAM role has all the advantages of the [AWS IAM Role](aws-service-connector.md#aws-iam-role) authentication method plus the added benefit of not requiring any explicit credentials to be configured and stored: * the connector will [generate temporary STS tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials) upon request by [calling the AssumeRole STS API](https://docs.aws.amazon.com/IAM/latest/UserGuide/id\_credentials\_temp\_request.html#api\_assumerole). * allows implementing [a two layer authentication scheme](best-security-practices.md#impersonating-accounts-and-assuming-roles) that keeps the set of permissions associated with implicit credentials down to the bare minimum and grants permissions to the privilege-bearing IAM role instead. * one or more optional [IAM session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access\_policies.html#policies\_session) may also be configured to further restrict the permissions of the generated STS tokens. If not specified, IAM session policies are automatically configured for the generated STS tokens [to restrict them to the minimum set of permissions required to access the target resource](best-security-practices.md#generating-temporary-and-down-scoped-credentials). Refer to the documentation for each supported Resource Type for the complete list of AWS permissions automatically granted to the generated STS tokens. * the default expiration period for generated STS tokens is 1 hour with a minimum of 15 minutes up to the maximum session duration setting configured for the IAM role (default is 1 hour). If you need longer-lived tokens, you can configure the IAM role to use a higher maximum expiration value (up to 12 hours) or use the AWS Federation Token or AWS Session Token authentication methods. Note that the discovered credentials inherit the full set of permissions of the local AWS client configuration, environment variables, or remote AWS IAM role. Depending on the extent of those permissions, this authentication instead method might not be recommended for production use, as it can lead to accidental privilege escalation. It is recommended to also configure an IAM role when using the implicit authentication method, or to use the [AWS IAM Role](aws-service-connector.md#aws-iam-role), [AWS Session Token](aws-service-connector.md#aws-session-token), or [AWS Federation Token](aws-service-connector.md#aws-federation-token) authentication methods instead to limit the validity and/or permissions of the credentials being issued to connector clients. {% hint style="info" %} If you need to access an EKS Kubernetes cluster with this authentication method, please be advised that the EKS cluster's `aws-auth` ConfigMap may need to be manually configured to allow authentication with the implicit IAM user or role picked up by the Service Connector. For more information, [see this documentation](https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html). {% endhint %} An AWS region is required and the connector may only be used to access AWS resources in the specified region.
Example configuration The following assumes the local AWS CLI has a `connectors` AWS CLI profile already configured with credentials: ```sh AWS_PROFILE=connectors zenml service-connector register aws-implicit --type aws --auth-method implicit --region=us-east-1 ``` {% code title="Example Command Output" %} ``` ⠸ Registering service connector 'aws-implicit'... Successfully registered service connector `aws-implicit` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┃ │ s3://zenml-public-datasets ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} No credentials are stored with the Service Connector: ```sh zenml service-connector describe aws-implicit ``` {% code title="Example Command Output" %} ``` Service connector 'aws-implicit' of type 'aws' with id 'e3853748-34a0-4d78-8006-00422ad32884' is owned by user 'default' and is 'private'. 'aws-implicit' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ ID │ 9a810521-ef41-4e45-bb48-8569c5943dc6 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ aws-implicit ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ implicit ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔶 aws-generic, 📦 s3-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 18:08:37.969928 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 18:08:37.969930 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────┼───────────┨ ┃ region │ us-east-1 ┃ ┗━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %} Verifying access to resources (note the `AWS_PROFILE` environment points to the same AWS CLI profile used during registration, but may yield different results with a different profile, which is why this method is not suitable for reproducible results): ```sh AWS_PROFILE=connectors zenml service-connector verify aws-implicit --resource-type s3-bucket ``` {% code title="Example Command Output" %} ``` ⠸ Verifying service connector 'aws-implicit'... Service connector 'aws-implicit' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼───────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┃ │ s3://zenml-public-datasets ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector verify aws-implicit --resource-type s3-bucket ``` {% code title="Example Command Output" %} ``` ⠸ Verifying service connector 'aws-implicit'... Service connector 'aws-implicit' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼────────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://sagemaker-studio-907999144431-m11qlsdyqr8 ┃ ┃ │ s3://sagemaker-studio-d8a14tvjsmb ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} Depending on the environment, clients are issued either temporary STS tokens or long-lived credentials, which is a reason why this method isn't well suited for production: ```sh AWS_PROFILE=zenml zenml service-connector describe aws-implicit --resource-type s3-bucket --resource-id zenfiles --client ``` {% code title="Example Command Output" %} ``` INFO:botocore.credentials:Found credentials in shared credentials file: ~/.aws/credentials Service connector 'aws-implicit (s3-bucket | s3://zenfiles client)' of type 'aws' with id 'e3853748-34a0-4d78-8006-00422ad32884' is owned by user 'default' and is 'private'. 'aws-implicit (s3-bucket | s3://zenfiles client)' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ ID │ 9a810521-ef41-4e45-bb48-8569c5943dc6 ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ NAME │ aws-implicit (s3-bucket | s3://zenfiles client) ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ AUTH METHOD │ sts-token ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 📦 s3-bucket ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ s3://zenfiles ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ SECRET ID │ ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ EXPIRES IN │ 59m57s ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 18:13:34.146659 ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 18:13:34.146664 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_session_token │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector describe aws-implicit --resource-type s3-bucket --resource-id s3://sagemaker-studio-d8a14tvjsmb --client ``` {% code title="Example Command Output" %} ``` INFO:botocore.credentials:Found credentials in shared credentials file: ~/.aws/credentials Service connector 'aws-implicit (s3-bucket | s3://sagemaker-studio-d8a14tvjsmb client)' of type 'aws' with id 'e3853748-34a0-4d78-8006-00422ad32884' is owned by user 'default' and is 'private'. 'aws-implicit (s3-bucket | s3://sagemaker-studio-d8a14tvjsmb client)' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ ID │ 9a810521-ef41-4e45-bb48-8569c5943dc6 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ NAME │ aws-implicit (s3-bucket | s3://sagemaker-studio-d8a14tvjsmb client) ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ secret-key ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 📦 s3-bucket ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ s3://sagemaker-studio-d8a14tvjsmb ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 18:12:42.066053 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 18:12:42.066055 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %}
### AWS Secret Key [Long-lived AWS credentials](best-security-practices.md#long-lived-credentials-api-keys-account-keys) consisting of an AWS access key ID and secret access key associated with an AWS IAM user or AWS account root user (not recommended). This method is preferred during development and testing due to its simplicity and ease of use. It is not recommended as a direct authentication method for production use cases because the clients have direct access to long-lived credentials and are granted the full set of permissions of the IAM user or AWS account root user associated with the credentials. For production, it is recommended to use [the AWS IAM Role](aws-service-connector.md#aws-iam-role), [AWS Session Token](aws-service-connector.md#aws-session-token), or [AWS Federation Token](aws-service-connector.md#aws-federation-token) authentication method instead. An AWS region is required and the connector may only be used to access AWS resources in the specified region. If you already have the local AWS CLI set up with these credentials, they will be automatically picked up when auto-configuration is used (see the example below).
Example auto-configuration The following assumes the local AWS CLI has a `connectors` AWS CLI profile configured with an AWS Secret Key. We need to force the ZenML CLI to use the Secret Key authentication by passing the `--auth-method secret-key` option, otherwise it would automatically use [the AWS Session Token authentication method](aws-service-connector.md#aws-session-token) as an extra precaution: ```sh AWS_PROFILE=connectors zenml service-connector register aws-secret-key --type aws --auth-method secret-key --auto-configure ``` {% code title="Example Command Output" %} ``` ⠸ Registering service connector 'aws-secret-key'... Successfully registered service connector `aws-secret-key` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The AWS Secret Key was lifted up from the local host: ```sh zenml service-connector describe aws-secret-key ``` {% code title="Example Command Output" %} ``` Service connector 'aws-secret-key' of type 'aws' with id 'a1b07c5a-13af-4571-8e63-57a809c85790' is owned by user 'default' and is 'private'. 'aws-secret-key' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ ID │ 37c97fa0-fa47-4d55-9970-e2aa6e1b50cf ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ aws-secret-key ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ secret-key ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔶 aws-generic, 📦 s3-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ b889efe1-0e23-4e2d-afc3-bdd785ee2d80 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 19:23:39.982950 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 19:23:39.982952 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %}
### AWS STS Token Uses [temporary STS tokens](best-security-practices.md#short-lived-credentials) explicitly configured by the user or auto-configured from a local environment. This method has the major limitation that the user must regularly generate new tokens and update the connector configuration as STS tokens expire. On the other hand, this method is ideal in cases where the connector only needs to be used for a short period of time, such as sharing access temporarily with someone else in your team. Using other authentication methods like [IAM role](aws-service-connector.md#aws-iam-role), [Session Token](aws-service-connector.md#aws-session-token), or [Federation Token](aws-service-connector.md#aws-federation-token) will automatically generate and refresh STS tokens for clients upon request. An AWS region is required and the connector may only be used to access AWS resources in the specified region.
Example auto-configuration Fetching STS tokens from the local AWS CLI is possible if the AWS CLI is already configured with valid credentials. In our example, the `connectors` AWS CLI profile is configured with an IAM user Secret Key. We need to force the ZenML CLI to use the STS token authentication by passing the `--auth-method sts-token` option, otherwise it would automatically use [the session token authentication method](aws-service-connector.md#aws-session-token): ```sh AWS_PROFILE=connectors zenml service-connector register aws-sts-token --type aws --auto-configure --auth-method sts-token ``` {% code title="Example Command Output" %} ``` ⠸ Registering service connector 'aws-sts-token'... Successfully registered service connector `aws-sts-token` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The Service Connector configuration shows that the connector is configured with an STS token: ```sh zenml service-connector describe aws-sts-token ``` {% code title="Example Command Output" %} ``` Service connector 'aws-sts-token' of type 'aws' with id '63e14350-6719-4255-b3f5-0539c8f7c303' is owned by user 'default' and is 'private'. 'aws-sts-token' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ ID │ a05ef4ef-92cb-46b2-8a3a-a48535adccaf ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ aws-sts-token ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ sts-token ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔶 aws-generic, 📦 s3-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ bffd79c7-6d76-483b-9001-e9dda4e865ae ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ 11h58m24s ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 19:25:40.278681 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 19:25:40.278684 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_session_token │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %} Note the temporary nature of the Service Connector. It will become unusable in 12 hours: ```sh zenml service-connector list --name aws-sts-token ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼───────────────┼──────────────────────────────────────┼────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ aws-sts-token │ a05ef4ef-92cb-46b2-8a3a-a48535adccaf │ 🔶 aws │ 🔶 aws-generic │ │ ➖ │ default │ 11h57m51s │ ┃ ┃ │ │ │ │ 📦 s3-bucket │ │ │ │ │ ┃ ┃ │ │ │ │ 🌀 kubernetes-cluster │ │ │ │ │ ┃ ┃ │ │ │ │ 🐳 docker-registry │ │ │ │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┛ ``` {% endcode %}
### AWS IAM Role Generates [temporary STS credentials](best-security-practices.md#impersonating-accounts-and-assuming-roles) by assuming an AWS IAM role. This authentication method still requires credentials to be explicitly configured. If your ZenML server is running in AWS and you're looking for an alternative that uses implicit credentials while at the same time benefits from all the security advantages of assuming an IAM role, you should [use the implicit authentication method with a configured IAM role](aws-service-connector.md#implicit-authentication) instead. The connector needs to be configured with the IAM role to be assumed accompanied by an AWS secret key associated with an IAM user or an STS token associated with another IAM role. The IAM user or IAM role must have permission to assume the target IAM role. The connector will [generate temporary STS tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials) upon request by [calling the AssumeRole STS API](https://docs.aws.amazon.com/IAM/latest/UserGuide/id\_credentials\_temp\_request.html#api\_assumerole). [The best practice implemented with this authentication scheme](best-security-practices.md#impersonating-accounts-and-assuming-roles) is to keep the set of permissions associated with the primary IAM user or IAM role down to the bare minimum and grant permissions to the privilege-bearing IAM role instead. An AWS region is required and the connector may only be used to access AWS resources in the specified region. One or more optional [IAM session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access\_policies.html#policies\_session) may also be configured to further restrict the permissions of the generated STS tokens. If not specified, IAM session policies are automatically configured for the generated STS tokens [to restrict them to the minimum set of permissions required to access the target resource](best-security-practices.md#generating-temporary-and-down-scoped-credentials). Refer to the documentation for each supported Resource Type for the complete list of AWS permissions automatically granted to the generated STS tokens. The default expiration period for generated STS tokens is 1 hour with a minimum of 15 minutes up to the maximum session duration setting configured for the IAM role (default is 1 hour). If you need longer-lived tokens, you can configure the IAM role to use a higher maximum expiration value (up to 12 hours) or use the AWS Federation Token or AWS Session Token authentication methods. For more information on IAM roles and the AssumeRole AWS API, see [the official AWS documentation on the subject](https://docs.aws.amazon.com/IAM/latest/UserGuide/id\_credentials\_temp\_request.html#api\_assumerole). For more information about the difference between this method and the AWS Federation Token authentication method, [consult this AWS documentation page](https://aws.amazon.com/blogs/security/understanding-the-api-options-for-securely-delegating-access-to-your-aws-account/).
Example auto-configuration The following assumes the local AWS CLI has a `zenml` AWS CLI profile already configured with an AWS Secret Key and an IAM role to be assumed: ```sh AWS_PROFILE=zenml zenml service-connector register aws-iam-role --type aws --auto-configure ``` {% code title="Example Command Output" %} ``` ⠸ Registering service connector 'aws-iam-role'... Successfully registered service connector `aws-iam-role` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The Service Connector configuration shows an IAM role and long-lived credentials: ```sh zenml service-connector describe aws-iam-role ``` {% code title="Example Command Output" %} ``` Service connector 'aws-iam-role' of type 'aws' with id '8e499202-57fd-478e-9d2f-323d76d8d211' is owned by user 'default' and is 'private'. 'aws-iam-role' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ ID │ 2b99de14-6241-4194-9608-b9d478e1bcfc ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ aws-iam-role ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ iam-role ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔶 aws-generic, 📦 s3-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ 87795fdd-b70e-4895-b0dd-8bca5fd4d10e ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ 3600s ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 19:28:31.679843 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 19:28:31.679848 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼────────────────────────────────────────────────────────────────────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼────────────────────────────────────────────────────────────────────────┨ ┃ role_arn │ arn:aws:iam::715803424590:role/OrganizationAccountRestrictedAccessRole ┃ ┠───────────────────────┼────────────────────────────────────────────────────────────────────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼────────────────────────────────────────────────────────────────────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} However, clients receive temporary STS tokens instead of the AWS Secret Key configured in the connector (note the authentication method, expiration time, and credentials): ```sh zenml service-connector describe aws-iam-role --resource-type s3-bucket --resource-id zenfiles --client ``` {% code title="Example Command Output" %} ``` Service connector 'aws-iam-role (s3-bucket | s3://zenfiles client)' of type 'aws' with id '8e499202-57fd-478e-9d2f-323d76d8d211' is owned by user 'default' and is 'private'. 'aws-iam-role (s3-bucket | s3://zenfiles client)' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ ID │ 2b99de14-6241-4194-9608-b9d478e1bcfc ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ NAME │ aws-iam-role (s3-bucket | s3://zenfiles client) ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ AUTH METHOD │ sts-token ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 📦 s3-bucket ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ s3://zenfiles ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ SECRET ID │ ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ EXPIRES IN │ 59m56s ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 19:30:51.462445 ┃ ┠──────────────────┼─────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 19:30:51.462449 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_session_token │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %}
### AWS Session Token Generates [temporary session STS tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials) for IAM users. The connector needs to be configured with an AWS secret key associated with an IAM user or AWS account root user (not recommended). The connector will [generate temporary STS tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials) upon request by calling [the GetSessionToken STS API](https://docs.aws.amazon.com/IAM/latest/UserGuide/id\_credentials\_temp\_request.html#api\_getsessiontoken). The STS tokens have an expiration period longer than those issued through the [AWS IAM Role authentication method](aws-service-connector.md#aws-iam-role) and are more suitable for long-running processes that cannot automatically re-generate credentials upon expiration. An AWS region is required and the connector may only be used to access AWS resources in the specified region. The default expiration period for generated STS tokens is 12 hours with a minimum of 15 minutes and a maximum of 36 hours. Temporary credentials obtained by using the AWS account root user credentials (not recommended) have a maximum duration of 1 hour. As a precaution, when long-lived credentials (i.e. AWS Secret Keys) are detected on your environment by the Service Connector during auto-configuration, this authentication method is automatically chosen instead of the AWS [Secret Key authentication method](aws-service-connector.md#aws-secret-key) alternative. Generated STS tokens inherit the full set of permissions of the IAM user or AWS account root user that is calling the GetSessionToken API. Depending on your security needs, this may not be suitable for production use, as it can lead to accidental privilege escalation. Instead, it is recommended to use the AWS Federation Token or [AWS IAM Role authentication](aws-service-connector.md#aws-iam-role) methods to restrict the permissions of the generated STS tokens. For more information on session tokens and the GetSessionToken AWS API, see [the official AWS documentation on the subject](https://docs.aws.amazon.com/IAM/latest/UserGuide/id\_credentials\_temp\_request.html#api\_getsessiontoken).
Example auto-configuration The following assumes the local AWS CLI has a `connectors` AWS CLI profile already configured with an AWS Secret Key: ```sh AWS_PROFILE=connectors zenml service-connector register aws-session-token --type aws --auth-method session-token --auto-configure ``` {% code title="Example Command Output" %} ``` ⠸ Registering service connector 'aws-session-token'... Successfully registered service connector `aws-session-token` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The Service Connector configuration shows long-lived credentials were lifted from the local environment and the AWS Session Token authentication method was configured: ```sh zenml service-connector describe aws-session-token ``` {% code title="Example Command Output" %} ``` Service connector 'aws-session-token' of type 'aws' with id '3ae3e595-5cbc-446e-be64-e54e854e0e3f' is owned by user 'default' and is 'private'. 'aws-session-token' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ ID │ c0f8e857-47f9-418b-a60f-c3b03023da54 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ aws-session-token ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ session-token ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔶 aws-generic, 📦 s3-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ 16f35107-87ef-4a86-bbae-caa4a918fc15 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ 43200s ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 19:31:54.971869 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 19:31:54.971871 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %} However, clients receive temporary STS tokens instead of the AWS Secret Key configured in the connector (note the authentication method, expiration time, and credentials): ```sh zenml service-connector describe aws-session-token --resource-type s3-bucket --resource-id zenfiles --client ``` {% code title="Example Command Output" %} ``` Service connector 'aws-session-token (s3-bucket | s3://zenfiles client)' of type 'aws' with id '3ae3e595-5cbc-446e-be64-e54e854e0e3f' is owned by user 'default' and is 'private'. 'aws-session-token (s3-bucket | s3://zenfiles client)' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ ID │ c0f8e857-47f9-418b-a60f-c3b03023da54 ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ NAME │ aws-session-token (s3-bucket | s3://zenfiles client) ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ sts-token ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 📦 s3-bucket ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ s3://zenfiles ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ SECRET ID │ ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ 11h59m56s ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 19:35:24.090861 ┃ ┠──────────────────┼──────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 19:35:24.090863 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_session_token │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %}
### AWS Federation Token Generates [temporary STS tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials) for federated users by [impersonating another user](best-security-practices.md#impersonating-accounts-and-assuming-roles). The connector needs to be configured with an AWS secret key associated with an IAM user or AWS account root user (not recommended). The IAM user must have permission to call [the GetFederationToken STS API](https://docs.aws.amazon.com/IAM/latest/UserGuide/id\_credentials\_temp\_request.html#api\_getfederationtoken) (i.e. allow the `sts:GetFederationToken` action on the `*` IAM resource). The connector will generate temporary STS tokens upon request by calling the GetFederationToken STS API. These STS tokens have an expiration period longer than those issued through [the AWS IAM Role authentication method](aws-service-connector.md#aws-iam-role) and are more suitable for long-running processes that cannot automatically re-generate credentials upon expiration. An AWS region is required and the connector may only be used to access AWS resources in the specified region. One or more optional [IAM session policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access\_policies.html#policies\_session) may also be configured to further restrict the permissions of the generated STS tokens. If not specified, IAM session policies are automatically configured for the generated STS tokens [to restrict them to the minimum set of permissions required to access the target resource](best-security-practices.md#generating-temporary-and-down-scoped-credentials). Refer to the documentation for each supported Resource Type for the complete list of AWS permissions automatically granted to the generated STS tokens. {% hint style="warning" %} If this authentication method is used with [the generic AWS resource type](aws-service-connector.md#generic-aws-resource), a session policy MUST be explicitly specified, otherwise, the generated STS tokens will not have any permissions. {% endhint %} The default expiration period for generated STS tokens is 12 hours with a minimum of 15 minutes and a maximum of 36 hours. Temporary credentials obtained by using the AWS account root user credentials (not recommended) have a maximum duration of 1 hour. {% hint style="info" %} If you need to access an EKS Kubernetes cluster with this authentication method, please be advised that the EKS cluster's `aws-auth` ConfigMap may need to be manually configured to allow authentication with the federated user. For more information, [see this documentation](https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html). {% endhint %} For more information on user federation tokens, session policies, and the GetFederationToken AWS API, see [the official AWS documentation on the subject](https://docs.aws.amazon.com/IAM/latest/UserGuide/id\_credentials\_temp\_request.html#api\_getfederationtoken). For more information about the difference between this method and [the AWS IAM Role authentication method](aws-service-connector.md#aws-iam-role), [consult this AWS documentation page](https://aws.amazon.com/blogs/security/understanding-the-api-options-for-securely-delegating-access-to-your-aws-account/).
Example auto-configuration The following assumes the local AWS CLI has a `connectors` AWS CLI profile already configured with an AWS Secret Key: ```sh AWS_PROFILE=connectors zenml service-connector register aws-federation-token --type aws --auth-method federation-token --auto-configure ``` {% code title="Example Command Output" %} ``` ⠸ Registering service connector 'aws-federation-token'... Successfully registered service connector `aws-federation-token` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The Service Connector configuration shows long-lived credentials have been picked up from the local AWS CLI configuration: ```sh zenml service-connector describe aws-federation-token ``` {% code title="Example Command Output" %} ``` Service connector 'aws-federation-token' of type 'aws' with id '868b17d4-b950-4d89-a6c4-12e520e66610' is owned by user 'default' and is 'private'. 'aws-federation-token' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ ID │ e28c403e-8503-4cce-9226-8a7cd7934763 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ aws-federation-token ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ federation-token ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔶 aws-generic, 📦 s3-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ 958b840d-2a27-4f6b-808b-c94830babd99 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ 43200s ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 19:36:28.619751 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 19:36:28.619753 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %} However, clients receive temporary STS tokens instead of the AWS Secret Key configured in the connector (note the authentication method, expiration time, and credentials): ```sh zenml service-connector describe aws-federation-token --resource-type s3-bucket --resource-id zenfiles --client ``` {% code title="Example Command Output" %} ``` Service connector 'aws-federation-token (s3-bucket | s3://zenfiles client)' of type 'aws' with id '868b17d4-b950-4d89-a6c4-12e520e66610' is owned by user 'default' and is 'private'. 'aws-federation-token (s3-bucket | s3://zenfiles client)' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ ID │ e28c403e-8503-4cce-9226-8a7cd7934763 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ NAME │ aws-federation-token (s3-bucket | s3://zenfiles client) ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ sts-token ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 📦 s3-bucket ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ s3://zenfiles ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ SECRET ID │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ 11h59m56s ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 19:38:29.406986 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 19:38:29.406991 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_session_token │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %}
## Auto-configuration The AWS Service Connector allows [auto-discovering and fetching credentials](service-connectors-guide.md#auto-configuration) and configuration set up [by the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) during registration. The default AWS CLI profile is used unless the AWS\_PROFILE environment points to a different profile.
Auto-configuration example The following is an example of lifting AWS credentials granting access to the same set of AWS resources and services that the local AWS CLI is allowed to access. In this case, [the IAM role authentication method](aws-service-connector.md#aws-iam-role) was automatically detected: ```sh AWS_PROFILE=zenml zenml service-connector register aws-auto --type aws --auto-configure ``` {% code title="Example Command Output" %} ``` ⠹ Registering service connector 'aws-auto'... Successfully registered service connector `aws-auto` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://zenbytes-bucket ┃ ┃ │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The Service Connector configuration shows how credentials have automatically been fetched from the local AWS CLI configuration: ```sh zenml service-connector describe aws-auto ``` {% code title="Example Command Output" %} ``` Service connector 'aws-auto' of type 'aws' with id '9f3139fd-4726-421a-bc07-312d83f0c89e' is owned by user 'default' and is 'private'. 'aws-auto' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ ID │ 9cdc926e-55d7-49f0-838e-db5ac34bb7dc ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ aws-auto ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ iam-role ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔶 aws-generic, 📦 s3-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ a137151e-1778-4f50-b64b-7cf6c1f715f5 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ 3600s ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 19:39:11.958426 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 19:39:11.958428 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼────────────────────────────────────────────────────────────────────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼────────────────────────────────────────────────────────────────────────┨ ┃ role_arn │ arn:aws:iam::715803424590:role/OrganizationAccountRestrictedAccessRole ┃ ┠───────────────────────┼────────────────────────────────────────────────────────────────────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼────────────────────────────────────────────────────────────────────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
## Local client provisioning The local AWS CLI, Kubernetes `kubectl` CLI and the Docker CLI can be [configured with credentials extracted from or generated by a compatible AWS Service Connector](service-connectors-guide.md#configure-local-clients). Please note that unlike the configuration made possible through the AWS CLI, the Kubernetes and Docker credentials issued by the AWS Service Connector have a short lifetime and will need to be regularly refreshed. This is a byproduct of implementing a high-security profile. {% hint style="info" %} Configuring the local AWS CLI with credentials issued by the AWS Service Connector results in a local AWS CLI configuration profile being created with the name inferred from the first digits of the Service Connector UUID in the form -\. For example, a Service Connector with UUID `9f3139fd-4726-421a-bc07-312d83f0c89e` will result in a local AWS CLI configuration profile named `zenml-9f3139fd`. {% endhint %}
Local CLI configuration examples The following shows an example of configuring the local Kubernetes CLI to access an EKS cluster reachable through an AWS Service Connector: ```sh zenml service-connector list --name aws-session-token ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼───────────────────┼──────────────────────────────────────┼────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ aws-session-token │ c0f8e857-47f9-418b-a60f-c3b03023da54 │ 🔶 aws │ 🔶 aws-generic │ │ ➖ │ default │ │ ┃ ┃ │ │ │ │ 📦 s3-bucket │ │ │ │ │ ┃ ┃ │ │ │ │ 🌀 kubernetes-cluster │ │ │ │ │ ┃ ┃ │ │ │ │ 🐳 docker-registry │ │ │ │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┛ ``` {% endcode %} This checks the Kubernetes clusters that the AWS Service Connector has access to: ```sh zenml service-connector verify aws-session-token --resource-type kubernetes-cluster ``` {% code title="Example Command Output" %} ``` Service connector 'aws-session-token' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} Running the login CLI command will configure the local `kubectl` CLI to access the Kubernetes cluster: ```sh zenml service-connector login aws-session-token --resource-type kubernetes-cluster --resource-id zenhacks-cluster ``` {% code title="Example Command Output" %} ``` ⠇ Attempting to configure local client using service connector 'aws-session-token'... Cluster "arn:aws:eks:us-east-1:715803424590:cluster/zenhacks-cluster" set. Context "arn:aws:eks:us-east-1:715803424590:cluster/zenhacks-cluster" modified. Updated local kubeconfig with the cluster details. The current kubectl context was set to 'arn:aws:eks:us-east-1:715803424590:cluster/zenhacks-cluster'. The 'aws-session-token' Kubernetes Service Connector connector was used to successfully configure the local Kubernetes cluster client/SDK. ``` {% endcode %} The following can be used to check that the local `kubectl` CLI is correctly configured: ```sh kubectl cluster-info ``` {% code title="Example Command Output" %} ``` Kubernetes control plane is running at https://A5F8F4142FB12DDCDE9F21F6E9B07A18.gr7.us-east-1.eks.amazonaws.com CoreDNS is running at https://A5F8F4142FB12DDCDE9F21F6E9B07A18.gr7.us-east-1.eks.amazonaws.com/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy ``` {% endcode %} A similar process is possible with ECR container registries: ```sh zenml service-connector verify aws-session-token --resource-type docker-registry ``` {% code title="Example Command Output" %} ``` Service connector 'aws-session-token' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector login aws-session-token --resource-type docker-registry ``` {% code title="Example Command Output" %} ``` ⠏ Attempting to configure local client using service connector 'aws-session-token'... 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-session-token' Docker Service Connector connector was used to successfully configure the local Docker/OCI container registry client/SDK. ``` {% endcode %} The following can be used to check that the local Docker client is correctly configured: ```sh docker pull 715803424590.dkr.ecr.us-east-1.amazonaws.com/zenml-server ``` {% code title="Example Command Output" %} ``` Using default tag: latest latest: Pulling from zenml-server e9995326b091: Pull complete f3d7f077cdde: Pull complete 0db71afa16f3: Pull complete 6f0b5905c60c: Pull complete 9d2154d50fd1: Pull complete d072bba1f611: Pull complete 20e776588361: Pull complete 3ce69736a885: Pull complete c9c0554c8e6a: Pull complete bacdcd847a66: Pull complete 482033770844: Pull complete Digest: sha256:bf2cc3895e70dfa1ee1cd90bbfa599fa4cd8df837e27184bac1ce1cc239ecd3f Status: Downloaded newer image for 715803424590.dkr.ecr.us-east-1.amazonaws.com/zenml-server:latest 715803424590.dkr.ecr.us-east-1.amazonaws.com/zenml-server:latest ``` {% endcode %} It is also possible to update the local AWS CLI configuration with credentials extracted from the AWS Service Connector: ```sh zenml service-connector login aws-session-token --resource-type aws-generic ``` {% code title="Example Command Output" %} ``` Configured local AWS SDK profile 'zenml-c0f8e857'. The 'aws-session-token' AWS Service Connector connector was used to successfully configure the local Generic AWS resource client/SDK. ``` {% endcode %} A new profile is created in the local AWS CLI configuration holding the credentials. It can be used to access AWS resources and services, e.g.: ```sh aws --profile zenml-c0f8e857 s3 ls ```
## Stack Components use The [S3 Artifact Store Stack Component](../../../component-guide/artifact-stores/s3.md) can be connected to a remote AWS S3 bucket through an AWS Service Connector. The AWS Service Connector can also be used with any Orchestrator or Model Deployer stack component flavor that relies on Kubernetes clusters to manage workloads. This allows EKS Kubernetes container workloads to be managed without the need to configure and maintain explicit AWS or Kubernetes `kubectl` configuration contexts and credentials in the target environment and in the Stack Component. Similarly, Container Registry Stack Components can be connected to an ECR Container Registry through an AWS Service Connector. This allows container images to be built and published to ECR container registries without the need to configure explicit AWS credentials in the target environment or the Stack Component. ## End-to-end examples
EKS Kubernetes Orchestrator, S3 Artifact Store and ECR Container Registry with a multi-type AWS Service Connector This is an example of an end-to-end workflow involving Service Connectors that use a single multi-type AWS Service Connector to give access to multiple resources for multiple Stack Components. A complete ZenML Stack is registered and composed of the following Stack Components, all connected through the same Service Connector: * a [Kubernetes Orchestrator](../../../component-guide/orchestrators/kubernetes.md) connected to an EKS Kubernetes cluster * an [S3 Artifact Store](../../../component-guide/artifact-stores/s3.md) connected to an S3 bucket * an [ECR Container Registry](../../../component-guide/container-registries/aws.md) stack component connected to an ECR container registry * a local [Image Builder](../../../component-guide/image-builders/local.md) As a last step, a simple pipeline is run on the resulting Stack. 1. [Configure the local AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html) with valid IAM user account credentials with a wide range of permissions (i.e. by running `aws configure`) and install ZenML integration prerequisites: ```sh zenml integration install -y aws s3 ``` ```sh aws configure --profile connectors ``` {% code title="Example Command Output" %} ```` ```text AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY Default region name [None]: us-east-1 Default output format [None]: json ``` ```` {% endcode %} 2. Make sure the AWS Service Connector Type is available ```sh zenml service-connector list-types --type aws ``` {% code title="Example Command Output" %} ```` ```text ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ 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 │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` ```` {% endcode %} 3. Register a multi-type AWS Service Connector using auto-configuration ```sh AWS_PROFILE=connectors zenml service-connector register aws-demo-multi --type aws --auto-configure ``` {% code title="Example Command Output" %} ```` ```text ⠼ Registering service connector 'aws-demo-multi'... Successfully registered service connector `aws-demo-multi` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} ``` **NOTE**: from this point forward, we don't need the local AWS CLI credentials or the local AWS CLI at all. The steps that follow can be run on any machine regardless of whether it has been configured and authorized to access the AWS platform or not. ``` 4\. find out which S3 buckets, ECR registries, and EKS Kubernetes clusters we can gain access to. We'll use this information to configure the Stack Components in our minimal AWS stack: an S3 Artifact Store, a Kubernetes Orchestrator, and an ECR Container Registry. ```` ```sh zenml service-connector list-resources --resource-type s3-bucket ``` ```` {% code title="Example Command Output" %} ```` ```text 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 ┃ ┠──────────────────────────────────────┼─────────────────────┼────────────────┼───────────────┼───────────────────────────────────────┨ ┃ bf073e06-28ce-4a4a-8100-32e7cb99dced │ aws-demo-multi │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┃ │ │ │ │ s3://zenml-demos ┃ ┃ │ │ │ │ s3://zenml-generative-chat ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} ```` ```sh zenml service-connector list-resources --resource-type kubernetes-cluster ``` ```` {% code title="Example Command Output" %} ```` ```text 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 ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────┨ ┃ bf073e06-28ce-4a4a-8100-32e7cb99dced │ aws-demo-multi │ 🔶 aws │ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} ```` ```sh zenml service-connector list-resources --resource-type docker-registry ``` ```` {% code title="Example Command Output" %} ```` ```text 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 ┃ ┠──────────────────────────────────────┼────────────────────┼────────────────┼────────────────────┼─────────────────────────────────────────────────┨ ┃ bf073e06-28ce-4a4a-8100-32e7cb99dced │ aws-demo-multi │ 🔶 aws │ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 5. register and connect an S3 Artifact Store Stack Component to an S3 bucket: ```sh zenml artifact-store register s3-zenfiles --flavor s3 --path=s3://zenfiles ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully registered artifact_store `s3-zenfiles`. ``` ```` {% endcode %} ```` ```sh zenml artifact-store connect s3-zenfiles --connector aws-demo-multi ``` ```` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully connected artifact store `s3-zenfiles` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────┼────────────────┨ ┃ bf073e06-28ce-4a4a-8100-32e7cb99dced │ aws-demo-multi │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 6. register and connect a Kubernetes Orchestrator Stack Component to an EKS cluster: ```sh zenml orchestrator register eks-zenml-zenhacks --flavor kubernetes --synchronous=true --kubernetes_namespace=zenml-workloads ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully registered orchestrator `eks-zenml-zenhacks`. ``` ```` {% endcode %} ```` ```sh zenml orchestrator connect eks-zenml-zenhacks --connector aws-demo-multi ``` ```` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully connected orchestrator `eks-zenml-zenhacks` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────────────┼──────────────────┨ ┃ bf073e06-28ce-4a4a-8100-32e7cb99dced │ aws-demo-multi │ 🔶 aws │ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 7. Register and connect an EC GCP Container Registry Stack Component to an ECR container registry: ```sh zenml container-registry register ecr-us-east-1 --flavor aws --uri=715803424590.dkr.ecr.us-east-1.amazonaws.com ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully registered container_registry `ecr-us-east-1`. ``` ```` {% endcode %} ```` ```sh zenml container-registry connect ecr-us-east-1 --connector aws-demo-multi ``` ```` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully connected container registry `ecr-us-east-1` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────────┼──────────────────────────────────────────────┨ ┃ bf073e06-28ce-4a4a-8100-32e7cb99dced │ aws-demo-multi │ 🔶 aws │ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 8. Combine all Stack Components together into a Stack and set it as active (also throw in a local Image Builder for completion): ```sh zenml image-builder register local --flavor local ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (global) Successfully registered image_builder `local`. ``` ```` {% endcode %} ```` ```sh zenml stack register aws-demo -a s3-zenfiles -o eks-zenml-zenhacks -c ecr-us-east-1 -i local --set ``` ```` {% code title="Example Command Output" %} ```` ```text Connected to the ZenML server: 'https://stefan.develaws.zenml.io' Stack 'aws-demo' successfully registered! Active repository stack set to:'aws-demo' ``` ```` {% endcode %} 9. Finally, run a simple pipeline to prove that everything works as expected. We'll use the simplest pipelines possible for this example: ```python from zenml import pipeline, step @step def step_1() -> str: """Returns the `world` string.""" return "world" @step(enable_cache=False) def step_2(input_one: str, input_two: str) -> None: """Combines the two strings at its input and prints them.""" combined_str = f"{input_one} {input_two}" print(combined_str) @pipeline def my_pipeline(): output_step_one = step_1() step_2(input_one="hello", input_two=output_step_one) if __name__ == "__main__": my_pipeline() ``` Saving that to a `run.py` file and running it gives us: {% code title="Example Command Output" %} ```` ```text $ python run.py Building Docker image(s) for pipeline simple_pipeline. Building Docker image 715803424590.dkr.ecr.us-east-1.amazonaws.com/zenml:simple_pipeline-orchestrator. - Including user-defined requirements: boto3==1.26.76 - Including integration requirements: boto3, kubernetes==18.20.0, s3fs>2022.3.0,<=2023.4.0, sagemaker==2.117.0 No .dockerignore found, including all files inside build context. Step 1/10 : FROM zenmldocker/zenml:0.39.1-py3.8 Step 2/10 : WORKDIR /app Step 3/10 : COPY .zenml_user_requirements . Step 4/10 : RUN pip install --default-timeout=60 --no-cache-dir -r .zenml_user_requirements Step 5/10 : COPY .zenml_integration_requirements . Step 6/10 : RUN pip install --default-timeout=60 --no-cache-dir -r .zenml_integration_requirements Step 7/10 : ENV ZENML_ENABLE_REPO_INIT_WARNINGS=False Step 8/10 : ENV ZENML_CONFIG_PATH=/app/.zenconfig Step 9/10 : COPY . . Step 10/10 : RUN chmod -R a+rw . Amazon ECR requires you to create a repository before you can push an image to it. ZenML is trying to push the image 715803424590.dkr.ecr.us-east-1.amazonaws.com/zenml:simple_pipeline-orchestrator but could only detect the following repositories: []. We will try to push anyway, but in case it fails you need to create a repository named zenml. Pushing Docker image 715803424590.dkr.ecr.us-east-1.amazonaws.com/zenml:simple_pipeline-orchestrator. Finished pushing Docker image. Finished building Docker image(s). Running pipeline simple_pipeline on stack aws-demo (caching disabled) Waiting for Kubernetes orchestrator pod... Kubernetes orchestrator pod started. Waiting for pod of step step_1 to start... Step step_1 has started. Step step_1 has finished in 0.390s. Pod of step step_1 completed. Waiting for pod of step step_2 to start... Step step_2 has started. Hello World! Step step_2 has finished in 2.364s. Pod of step step_2 completed. Orchestration pod completed. Dashboard URL: https://stefan.develaws.zenml.io/default/pipelines/be5adfe9-45af-4709-a8eb-9522c01640ce/runs ``` ```` {% endcode %}
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/auth-management/azure-service-connector.md ================ --- description: >- Configuring Azure Service Connectors to connect ZenML to Azure resources such as Blob storage buckets, AKS Kubernetes clusters, and ACR container registries. --- # Azure Service Connector The ZenML Azure Service Connector facilitates the authentication and access to managed Azure services and resources. These encompass a range of resources, including blob storage containers, ACR repositories, and AKS clusters. This connector also supports [automatic configuration and detection of credentials](service-connectors-guide.md#auto-configuration) locally configured through the Azure CLI. This connector serves as a general means of accessing any Azure service by issuing credentials to clients. Additionally, the connector can handle specialized authentication for Azure blob storage, Docker and Kubernetes Python clients. It also allows for the configuration of local Docker and Kubernetes CLIs. ```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 │ │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` ## Prerequisites The Azure Service Connector is part of the Azure ZenML integration. You can either install the entire integration or use a pypi extra to install it independently of the integration: * `pip install "zenml[connectors-azure]"` installs only prerequisites for the Azure Service Connector Type * `zenml integration install azure` installs the entire Azure ZenML integration It is not required to [install and set up the Azure CLI](https://learn.microsoft.com/en-us/cli/azure/authenticate-azure-cli) on your local machine to use the Azure Service Connector to link Stack Components to Azure resources and services. However, it is recommended to do so if you are looking for a quick setup that includes using the auto-configuration Service Connector features. {% hint style="info" %} The auto-configuration option is limited to using temporary access tokens that don't work with Azure blob storage resources. To unlock the full power of the Azure Service Connector it is therefore recommended that you [configure and use an Azure service principal and its credentials](https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication-on-premises-apps?tabs=azure-portal). {% endhint %} ## Resource Types ### Generic Azure resource This resource type allows Stack Components to use the Azure Service Connector to connect to any Azure service or resource. When used by Stack Components, they are provided generic azure-identity credentials that can be used to create Azure python clients for any particular Azure service. This generic Azure resource type is meant to be used with Stack Components that are not represented by other, more specific resource type, like Azure blob storage containers, Kubernetes clusters or Docker registries. It should be accompanied by a matching set of Azure permissions that allow access to the set of remote resources required by the Stack Components. The resource name represents the name of the Azure subscription that the connector is authorized to access. ### Azure blob storage container Allows users to connect to Azure Blob containers. When used by Stack Components, they are provided a pre-configured Azure Blob Storage client. The configured credentials must have at least the following Azure IAM permissions associated with the blob storage account or containers that the connector that the connector will be allowed to access: * allow read and write access to blobs (e.g. the `Storage Blob Data Contributor` role) * allow listing the storage accounts (e.g. the `Reader and Data Access` role). This is only required if a storage account is not configured in the connector. * allow listing the containers in a storage account (e.g. the `Reader and Data Access` role) If set, the resource name must identify an Azure blob storage container using one of the following formats: * Azure blob container URI (canonical resource name): `{az|abfs}://{container-name}` * Azure blob container name: `{container-name}` If a storage account is configured in the connector, only blob storage containers in that storage account will be accessible. Otherwise, if a resource group is configured in the connector, only blob storage containers in storage accounts in that resource group will be accessible. Finally, if neither a storage account nor a resource group is configured in the connector, all blob storage containers in all accessible storage accounts will be accessible. {% hint style="warning" %} The only Azure authentication method that works with Azure blob storage resources is the service principal authentication method. {% endhint %} ### AKS Kubernetes cluster Allows Stack Components to access an AKS cluster as a standard Kubernetes cluster resource. When used by Stack Components, they are provided a pre-authenticated python-kubernetes client instance. The configured credentials must have at least the following Azure IAM permissions associated with the AKS clusters that the connector will be allowed to access: * allow listing the AKS clusters and fetching their credentials (e.g. the `Azure Kubernetes Service Cluster Admin Role` role) If set, the resource name must identify an EKS cluster using one of the following formats: * resource group scoped AKS cluster name (canonical): `[{resource-group}/]{cluster-name}` * AKS cluster name: `{cluster-name}` Given that the AKS cluster name is unique within a resource group, the resource group name may be included in the resource name to avoid ambiguity. If a resource group is configured in the connector, the resource group name in the resource name must match the configured resource group. If no resource group is configured in the connector and a resource group name is not included in the resource name, the connector will attempt to find the AKS cluster in any resource group. If a resource group is configured in the connector, only AKS clusters in that resource group will be accessible. ### ACR container registry Allows Stack Components to access one or more ACR registries as a standard Docker registry resource. When used by Stack Components, they are provided a pre-authenticated python-docker client instance. The configured credentials must have at least the following Azure IAM permissions associated with the ACR registries that the connector will be allowed to access: * allow access to pull and push images (e.g. the `AcrPull` and `AcrPush` roles) * allow access to list registries (e.g. the `Contributor` role) If set, the resource name must identify an ACR registry using one of the following formats: * ACR registry URI (canonical resource name): `[https://]{registry-name}.azurecr.io` * ACR registry name: `{registry-name}` If a resource group is configured in the connector, only ACR registries in that resource group will be accessible. If an authentication method other than the Azure service principal is used for authentication, the admin account must be enabled for the registry, otherwise, clients will not be able to authenticate to the registry. See the official Azure [documentation on the admin account](https://docs.microsoft.com/en-us/azure/container-registry/container-registry-authentication#admin-account) for more information. ## Authentication Methods ### Implicit authentication [Implicit authentication](best-security-practices.md#implicit-authentication) to Azure services using environment variables, local configuration files, workload or managed identities. {% hint style="warning" %} This method may constitute a security risk, because it can give users access to the same cloud resources and services that the ZenML Server itself is configured to access. For this reason, all implicit authentication methods are disabled by default and need to be explicitly enabled by setting the `ZENML_ENABLE_IMPLICIT_AUTH_METHODS` environment variable or the helm chart `enableImplicitAuthMethods` configuration option to `true` in the ZenML deployment. {% endhint %} This authentication method doesn't require any credentials to be explicitly configured. It automatically discovers and uses credentials from one of the following sources: * [environment variables](https://learn.microsoft.com/en-us/python/api/overview/azure/identity-readme?view=azure-python#environment-variables) * workload identity - if the application is deployed to an Azure Kubernetes Service with Managed Identity enabled. This option can only be used when running the ZenML server on an AKS cluster. * managed identity - if the application is deployed to an Azure host with Managed Identity enabled. This option can only be used when running the ZenML client or server on an Azure host. * Azure CLI - if a user has signed in via [the Azure CLI `az login` command](https://learn.microsoft.com/en-us/cli/azure/authenticate-azure-cli). This is the quickest and easiest way to authenticate to Azure services. However, the results depend on how ZenML is deployed and the environment where it is used and is thus not fully reproducible: * when used with the default local ZenML deployment or a local ZenML server, the credentials are the same as those used by the Azure CLI or extracted from local environment variables. * when connected to a ZenML server, this method only works if the ZenML server is deployed in Azure and will use the workload identity attached to the Azure resource where the ZenML server is running (e.g. an AKS cluster). The permissions of the managed identity may need to be adjusted to allows listing and accessing/describing the Azure resources that the connector is configured to access. Note that the discovered credentials inherit the full set of permissions of the local Azure CLI configuration, environment variables or remote Azure managed identity. Depending on the extent of those permissions, this authentication method might not be recommended for production use, as it can lead to accidental privilege escalation. Instead, it is recommended to use the Azure service principal authentication method to limit the validity and/or permissions of the credentials being issued to connector clients.
Example configuration The following assumes the local Azure CLI has already been configured with user account credentials by running the `az login` command: ```sh zenml service-connector register azure-implicit --type azure --auth-method implicit --auto-configure ``` {% code title="Example Command Output" %} ``` ⠙ Registering service connector 'azure-implicit'... Successfully registered service connector `azure-implicit` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 🇦 azure-generic │ ZenML Subscription ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 📦 blob-container │ az://demo-zenmlartifactstore ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ demo-zenml-demos/demo-zenml-terraform-cluster ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ demozenmlcontainerregistry.azurecr.io ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} No credentials are stored with the Service Connector: ```sh zenml service-connector describe azure-implicit ``` {% code title="Example Command Output" %} ``` Service connector 'azure-implicit' of type 'azure' with id 'ad645002-0cd4-4d4f-ae20-499ce888a00a' is owned by user 'default' and is 'private'. 'azure-implicit' azure Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ ID │ ad645002-0cd4-4d4f-ae20-499ce888a00a ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ azure-implicit ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🇦 azure ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ implicit ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🇦 azure-generic, 📦 blob-container, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-05 09:47:42.415949 ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-05 09:47:42.415954 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
### Azure Service Principal Azure service principal credentials consists of an Azure client ID and client secret. These credentials are used to authenticate clients to Azure services. For this authentication method, the Azure Service Connector requires [an Azure service principal to be created](https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication-on-premises-apps?tabs=azure-portal) and a client secret to be generated.
Example configuration The following assumes an Azure service principal was configured with a client secret and has permissions to access an Azure blob storage container, an AKS Kubernetes cluster and an ACR container registry. The service principal client ID, tenant ID and client secret are then used to configure the Azure Service Connector. ```sh zenml service-connector register azure-service-principal --type azure --auth-method service-principal --tenant_id=a79f3633-8f45-4a74-a42e-68871c17b7fb --client_id=8926254a-8c3f-430a-a2fd-bdab234d491e --client_secret=AzureSuperSecret ``` {% code title="Example Command Output" %} ``` ⠙ Registering service connector 'azure-service-principal'... Successfully registered service connector `azure-service-principal` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 🇦 azure-generic │ ZenML Subscription ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 📦 blob-container │ az://demo-zenmlartifactstore ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ demo-zenml-demos/demo-zenml-terraform-cluster ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ demozenmlcontainerregistry.azurecr.io ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The Service Connector configuration shows that the connector is configured with service principal credentials: ```sh zenml service-connector describe azure-service-principal ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ ID │ 273d2812-2643-4446-82e6-6098b8ccdaa4 ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ azure-service-principal ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🇦 azure ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ service-principal ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🇦 azure-generic, 📦 blob-container, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ 50d9f230-c4ea-400e-b2d7-6b52ba2a6f90 ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-20 19:16:26.802374 ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-20 19:16:26.802378 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────┼──────────────────────────────────────┨ ┃ tenant_id │ a79ff333-8f45-4a74-a42e-68871c17b7fb ┃ ┠───────────────┼──────────────────────────────────────┨ ┃ client_id │ 8926254a-8c3f-430a-a2fd-bdab234d491e ┃ ┠───────────────┼──────────────────────────────────────┨ ┃ client_secret │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
### Azure Access Token Uses [temporary Azure access tokens](best-security-practices.md#short-lived-credentials) explicitly configured by the user or auto-configured from a local environment. This method has the major limitation that the user must regularly generate new tokens and update the connector configuration as API tokens expire. On the other hand, this method is ideal in cases where the connector only needs to be used for a short period of time, such as sharing access temporarily with someone else in your team. This is the authentication method used during auto-configuration, if you have [the local Azure CLI set up with credentials](https://learn.microsoft.com/en-us/cli/azure/authenticate-azure-cli). The connector will generate an access token from the Azure CLI credentials and store it in the connector configuration. {% hint style="warning" %} Given that Azure access tokens are scoped to a particular Azure resource and the access token generated during auto-configuration is scoped to the Azure Management API, this method does not work with Azure blob storage resources. You should use [the Azure service principal authentication method](azure-service-connector.md#azure-service-principal) for blob storage resources instead. {% endhint %}
Example auto-configuration Fetching Azure session tokens from the local Azure CLI is possible if the Azure CLI is already configured with valid credentials (i.e. by running `az login`): ```sh zenml service-connector register azure-session-token --type azure --auto-configure ``` {% code title="Example Command Output" %} ``` ⠙ Registering service connector 'azure-session-token'... connector authorization failure: the 'access-token' authentication method is not supported for blob storage resources Successfully registered service connector `azure-session-token` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 🇦 azure-generic │ ZenML Subscription ┃ ┠───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 📦 blob-container │ 💥 error: connector authorization failure: the 'access-token' authentication method is not supported for blob storage resources ┃ ┠───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ demo-zenml-demos/demo-zenml-terraform-cluster ┃ ┠───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ demozenmlcontainerregistry.azurecr.io ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector describe azure-session-token ``` {% code title="Example Command Output" %} ``` Service connector 'azure-session-token' of type 'azure' with id '94d64103-9902-4aa5-8ce4-877061af89af' is owned by user 'default' and is 'private'. 'azure-session-token' azure Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ ID │ 94d64103-9902-4aa5-8ce4-877061af89af ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ azure-session-token ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🇦 azure ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ access-token ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🇦 azure-generic, 📦 blob-container, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ b34f2e95-ae16-43b6-8ab6-f0ee33dbcbd8 ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ 42m25s ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-05 10:03:32.646351 ┃ ┠──────────────────┼────────────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-05 10:03:32.646352 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━┯━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────┼──────────┨ ┃ token │ [HIDDEN] ┃ ┗━━━━━━━━━━┷━━━━━━━━━━┛ ``` {% endcode %} Note the temporary nature of the Service Connector. It will expire and become unusable in approximately 1 hour: ```sh zenml service-connector list --name azure-session-token ``` {% code title="Example Command Output" %} ``` Could not import GCP service connector: No module named 'google.api_core'. ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼─────────────────────┼──────────────────────────────────────┼──────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ azure-session-token │ 94d64103-9902-4aa5-8ce4-877061af89af │ 🇦 azure │ 🇦 azure-generic │ │ ➖ │ default │ 40m58s │ ┃ ┃ │ │ │ │ 📦 blob-container │ │ │ │ │ ┃ ┃ │ │ │ │ 🌀 kubernetes-cluster │ │ │ │ │ ┃ ┃ │ │ │ │ 🐳 docker-registry │ │ │ │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┛ ``` {% endcode %}
## Auto-configuration The Azure Service Connector allows [auto-discovering and fetching credentials](service-connectors-guide.md#auto-configuration) and [configuration set up by the Azure CLI](https://learn.microsoft.com/en-us/cli/azure/authenticate-azure-cli) on your local host. {% hint style="warning" %} The Azure service connector auto-configuration comes with two limitations: 1. it can only pick up temporary Azure access tokens and therefore cannot be used for long-term authentication scenarios 2. it doesn't support authenticating to the Azure blob storage service. [The Azure service principal authentication method](azure-service-connector.md#azure-service-principal) can be used instead. {% endhint %} For an auto-configuration example, please refer to the [section about Azure access tokens](azure-service-connector.md#azure-access-token). ## Local client provisioning The local Azure CLI, Kubernetes `kubectl` CLI and the Docker CLI can be [configured with credentials extracted from or generated by a compatible Azure Service Connector](service-connectors-guide.md#configure-local-clients). {% hint style="info" %} Note that the Azure local CLI can only be configured with credentials issued by the Azure Service Connector if the connector is configured with the [service principal authentication method](azure-service-connector.md#azure-service-principal). {% endhint %}
Local CLI configuration examples The following shows an example of configuring the local Kubernetes CLI to access an AKS cluster reachable through an Azure Service Connector: ```sh zenml service-connector list --name azure-service-principal ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼─────────────────────────┼──────────────────────────────────────┼──────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ azure-service-principal │ 3df920bc-120c-488a-b7fc-0e79bc8b021a │ 🇦 azure │ 🇦 azure-generic │ │ ➖ │ default │ │ ┃ ┃ │ │ │ │ 📦 blob-container │ │ │ │ │ ┃ ┃ │ │ │ │ 🌀 kubernetes-cluster │ │ │ │ │ ┃ ┃ │ │ │ │ 🐳 docker-registry │ │ │ │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┛ ``` {% endcode %} The verify CLI command can be used to list all Kubernetes clusters accessible through the Azure Service Connector: ```sh zenml service-connector verify azure-service-principal --resource-type kubernetes-cluster ``` {% code title="Example Command Output" %} ``` ⠙ Verifying service connector 'azure-service-principal'... Service connector 'azure-service-principal' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ demo-zenml-demos/demo-zenml-terraform-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The login CLI command can be used to configure the local Kubernetes CLI to access a Kubernetes cluster reachable through an Azure Service Connector: ```sh zenml service-connector login azure-service-principal --resource-type kubernetes-cluster --resource-id demo-zenml-demos/demo-zenml-terraform-cluster ``` {% code title="Example Command Output" %} ``` ⠙ Attempting to configure local client using service connector 'azure-service-principal'... Updated local kubeconfig with the cluster details. The current kubectl context was set to 'demo-zenml-terraform-cluster'. The 'azure-service-principal' Kubernetes Service Connector connector was used to successfully configure the local Kubernetes cluster client/SDK. ``` {% endcode %} The local Kubernetes CLI can now be used to interact with the Kubernetes cluster: ```sh kubectl cluster-info ``` {% code title="Example Command Output" %} ``` Kubernetes control plane is running at https://demo-43c5776f7.hcp.westeurope.azmk8s.io:443 CoreDNS is running at https://demo-43c5776f7.hcp.westeurope.azmk8s.io:443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy Metrics-server is running at https://demo-43c5776f7.hcp.westeurope.azmk8s.io:443/api/v1/namespaces/kube-system/services/https:metrics-server:/proxy ``` {% endcode %} A similar process is possible with ACR container registries: ```sh zenml service-connector verify azure-service-principal --resource-type docker-registry ``` {% code title="Example Command Output" %} ``` ⠦ Verifying service connector 'azure-service-principal'... Service connector 'azure-service-principal' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠────────────────────┼───────────────────────────────────────┨ ┃ 🐳 docker-registry │ demozenmlcontainerregistry.azurecr.io ┃ ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector login azure-service-principal --resource-type docker-registry --resource-id demozenmlcontainerregistry.azurecr.io ``` {% code title="Example Command Output" %} ``` ⠹ Attempting to configure local client using service connector 'azure-service-principal'... 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-service-principal' Docker Service Connector connector was used to successfully configure the local Docker/OCI container registry client/SDK. ``` {% endcode %} The local Docker CLI can now be used to interact with the container registry: ```sh docker push demozenmlcontainerregistry.azurecr.io/zenml:example_pipeline ``` {% code title="Example Command Output" %} ``` The push refers to repository [demozenmlcontainerregistry.azurecr.io/zenml] d4aef4f5ed86: Pushed 2d69a4ce1784: Pushed 204066eca765: Pushed 2da74ab7b0c1: Pushed 75c35abda1d1: Layer already exists 415ff8f0f676: Layer already exists c14cb5b1ec91: Layer already exists a1d005f5264e: Layer already exists 3a3fd880aca3: Layer already exists 149a9c50e18e: Layer already exists 1f6d3424b922: Layer already exists 8402c959ae6f: Layer already exists 419599cb5288: Layer already exists 8553b91047da: Layer already exists connectors: digest: sha256:a4cfb18a5cef5b2201759a42dd9fe8eb2f833b788e9d8a6ebde194765b42fe46 size: 3256 ``` {% endcode %} It is also possible to update the local Azure CLI configuration with credentials extracted from the Azure Service Connector: ```sh zenml service-connector login azure-service-principal --resource-type azure-generic ``` {% code title="Example Command Output" %} ``` Updated the local Azure CLI configuration with the connector's service principal credentials. The 'azure-service-principal' Azure Service Connector connector was used to successfully configure the local Generic Azure resource client/SDK. ``` {% endcode %}
## Stack Components use The [Azure Artifact Store Stack Component](../../../component-guide/artifact-stores/azure.md) can be connected to a remote Azure blob storage container through an Azure Service Connector. The Azure Service Connector can also be used with any Orchestrator or Model Deployer stack component flavor that relies on a Kubernetes clusters to manage workloads. This allows AKS Kubernetes container workloads to be managed without the need to configure and maintain explicit Azure or Kubernetes `kubectl` configuration contexts and credentials in the target environment or in the Stack Component itself. Similarly, Container Registry Stack Components can be connected to a ACR Container Registry through an Azure Service Connector. This allows container images to be built and published to private ACR container registries without the need to configure explicit Azure credentials in the target environment or the Stack Component. ## End-to-end examples
AKS Kubernetes Orchestrator, Azure Blob Storage Artifact Store and ACR Container Registry with a multi-type Azure Service Connector This is an example of an end-to-end workflow involving Service Connectors that uses a single multi-type Azure Service Connector to give access to multiple resources for multiple Stack Components. A complete ZenML Stack is registered composed of the following Stack Components, all connected through the same Service Connector: * a [Kubernetes Orchestrator](../../../component-guide/orchestrators/kubernetes.md) connected to an AKS Kubernetes cluster * a [Azure Blob Storage Artifact Store](../../../component-guide/artifact-stores/azure.md) connected to an Azure blob storage container * an [Azure Container Registry](../../../component-guide/container-registries/azure.md) connected to an ACR container registry * a local [Image Builder](../../../component-guide/image-builders/local.md) As a last step, a simple pipeline is run on the resulting Stack. This example needs to use a remote ZenML Server that is reachable from Azure. 1. Configure an Azure service principal with a client secret and give it permissions to access an Azure blob storage container, an AKS Kubernetes cluster and an ACR container registry. Also make sure you have the Azure ZenML integration installed: ```sh zenml integration install -y azure ``` 2. Make sure the Azure Service Connector Type is available ```sh zenml service-connector list-types --type azure ``` {% code title="Example Command Output" %} ```` ``` ┏━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ 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 │ │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` ```` {% endcode %} 3. Register a multi-type Azure Service Connector using the Azure service principal credentials set up at the first step. Note the resources that it has access to: ```sh zenml service-connector register azure-service-principal --type azure --auth-method service-principal --tenant_id=a79ff3633-8f45-4a74-a42e-68871c17b7fb --client_id=8926254a-8c3f-430a-a2fd-bdab234fd491e --client_secret=AzureSuperSecret ``` {% code title="Example Command Output" %} ```` ``` ⠸ Registering service connector 'azure-service-principal'... Successfully registered service connector `azure-service-principal` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 🇦 azure-generic │ ZenML Subscription ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 📦 blob-container │ az://demo-zenmlartifactstore ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ demo-zenml-demos/demo-zenml-terraform-cluster ┃ ┠───────────────────────┼───────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ demozenmlcontainerregistry.azurecr.io ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 4. register and connect an Azure Blob Storage Artifact Store Stack Component to an Azure blob container: ```sh zenml artifact-store register azure-demo --flavor azure --path=az://demo-zenmlartifactstore ``` {% code title="Example Command Output" %} ```` ``` Successfully registered artifact_store `azure-demo`. ``` ```` {% endcode %} ```` ```sh zenml artifact-store connect azure-demo --connector azure-service-principal ``` ```` {% code title="Example Command Output" %} ```` ``` Successfully connected artifact store `azure-demo` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼─────────────────────────┼────────────────┼───────────────────┼──────────────────────────────┨ ┃ f2316191-d20b-4348-a68b-f5e347862196 │ azure-service-principal │ 🇦 azure │ 📦 blob-container │ az://demo-zenmlartifactstore ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 5. register and connect a Kubernetes Orchestrator Stack Component to an AKS cluster: ```sh zenml orchestrator register aks-demo-cluster --flavor kubernetes --synchronous=true --kubernetes_namespace=zenml-workloads ``` {% code title="Example Command Output" %} ```` ``` Successfully registered orchestrator `aks-demo-cluster`. ``` ```` {% endcode %} ```` ```sh zenml orchestrator connect aks-demo-cluster --connector azure-service-principal ``` ```` {% code title="Example Command Output" %} ```` ``` Successfully connected orchestrator `aks-demo-cluster` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼─────────────────────────┼────────────────┼───────────────────────┼───────────────────────────────────────────────┨ ┃ f2316191-d20b-4348-a68b-f5e347862196 │ azure-service-principal │ 🇦 azure │ 🌀 kubernetes-cluster │ demo-zenml-demos/demo-zenml-terraform-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 6. Register and connect an Azure Container Registry Stack Component to an ACR container registry: ```sh zenml container-registry register acr-demo-registry --flavor azure --uri=demozenmlcontainerregistry.azurecr.io ``` {% code title="Example Command Output" %} ```` ``` Successfully registered container_registry `acr-demo-registry`. ``` ```` {% endcode %} ```` ```sh zenml container-registry connect acr-demo-registry --connector azure-service-principal ``` ```` {% code title="Example Command Output" %} ```` ``` Successfully connected container registry `acr-demo-registry` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼─────────────────────────┼────────────────┼────────────────────┼───────────────────────────────────────┨ ┃ f2316191-d20b-4348-a68b-f5e347862196 │ azure-service-principal │ 🇦 azure │ 🐳 docker-registry │ demozenmlcontainerregistry.azurecr.io ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 7. Combine all Stack Components together into a Stack and set it as active (also throw in a local Image Builder for completion): ```sh zenml image-builder register local --flavor local ``` {% code title="Example Command Output" %} ```` ``` Running with active stack: 'default' (global) Successfully registered image_builder `local`. ``` ```` {% endcode %} ```` ```sh zenml stack register gcp-demo -a azure-demo -o aks-demo-cluster -c acr-demo-registry -i local --set ``` ```` {% code title="Example Command Output" %} ```` ``` Stack 'gcp-demo' successfully registered! Active repository stack set to:'gcp-demo' ``` ```` {% endcode %} 8. Finally, run a simple pipeline to prove that everything works as expected. We'll use the simplest pipelines possible for this example: ```python from zenml import pipeline, step @step def step_1() -> str: """Returns the `world` string.""" return "world" @step(enable_cache=False) def step_2(input_one: str, input_two: str) -> None: """Combines the two strings at its input and prints them.""" combined_str = f"{input_one} {input_two}" print(combined_str) @pipeline def my_pipeline(): output_step_one = step_1() step_2(input_one="hello", input_two=output_step_one) if __name__ == "__main__": my_pipeline() ``` Saving that to a `run.py` file and running it gives us: {% code title="Example Command Output" %} ```` ``` $ python run.py Building Docker image(s) for pipeline simple_pipeline. Building Docker image demozenmlcontainerregistry.azurecr.io/zenml:simple_pipeline-orchestrator. - Including integration requirements: adlfs==2021.10.0, azure-identity==1.10.0, azure-keyvault-keys, azure-keyvault-secrets, azure-mgmt-containerservice>=20.0.0, azureml-core==1.48.0, kubernetes, kubernetes==18.20.0 No .dockerignore found, including all files inside build context. Step 1/10 : FROM zenmldocker/zenml:0.40.0-py3.8 Step 2/10 : WORKDIR /app Step 3/10 : COPY .zenml_user_requirements . Step 4/10 : RUN pip install --default-timeout=60 --no-cache-dir -r .zenml_user_requirements Step 5/10 : COPY .zenml_integration_requirements . Step 6/10 : RUN pip install --default-timeout=60 --no-cache-dir -r .zenml_integration_requirements Step 7/10 : ENV ZENML_ENABLE_REPO_INIT_WARNINGS=False Step 8/10 : ENV ZENML_CONFIG_PATH=/app/.zenconfig Step 9/10 : COPY . . Step 10/10 : RUN chmod -R a+rw . Pushing Docker image demozenmlcontainerregistry.azurecr.io/zenml:simple_pipeline-orchestrator. Finished pushing Docker image. Finished building Docker image(s). Running pipeline simple_pipeline on stack gcp-demo (caching disabled) Waiting for Kubernetes orchestrator pod... Kubernetes orchestrator pod started. Waiting for pod of step simple_step_one to start... Step simple_step_one has started. INFO:azure.identity._internal.get_token_mixin:ClientSecretCredential.get_token succeeded INFO:azure.identity._internal.get_token_mixin:ClientSecretCredential.get_token succeeded INFO:azure.identity._internal.get_token_mixin:ClientSecretCredential.get_token succeeded INFO:azure.identity.aio._internal.get_token_mixin:ClientSecretCredential.get_token succeeded Step simple_step_one has finished in 0.396s. Pod of step simple_step_one completed. Waiting for pod of step simple_step_two to start... Step simple_step_two has started. INFO:azure.identity._internal.get_token_mixin:ClientSecretCredential.get_token succeeded INFO:azure.identity._internal.get_token_mixin:ClientSecretCredential.get_token succeeded INFO:azure.identity.aio._internal.get_token_mixin:ClientSecretCredential.get_token succeeded Hello World! Step simple_step_two has finished in 3.203s. Pod of step simple_step_two completed. Orchestration pod completed. Dashboard URL: https://zenml.stefan.20.23.46.143.nip.io/default/pipelines/98c41e2a-1ab0-4ec9-8375-6ea1ab473686/runs ``` ```` {% endcode %}
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/auth-management/best-security-practices.md ================ --- description: >- Best practices concerning the various authentication methods implemented by Service Connectors. --- # Security best practices Service Connector Types, especially those targeted at cloud providers, offer a plethora of authentication methods matching those supported by remote cloud platforms. While there is no single authentication standard that unifies this process, there are some patterns that are easily identifiable and can be used as guidelines when deciding which authentication method to use to configure a Service Connector. This section explores some of those patterns and gives some advice regarding which authentication methods are best suited for your needs. {% hint style="info" %} This section may require some general knowledge about authentication and authorization to be properly understood. We tried to keep it simple and limit ourselves to talking about high-level concepts, but some areas may get a bit too technical. {% endhint %} ## Username and password {% hint style="danger" %} The key takeaway is this: you should avoid using your primary account password as authentication credentials as much as possible. If there are alternative authentication methods that you can use or other types of credentials (e.g. session tokens, API keys, API tokens), you should always try to use those instead. Ultimately, if you have no choice, be cognizant of the third parties you share your passwords with. If possible, they should never leave the premises of your local host or development environment. {% endhint %} This is the typical authentication method that uses a username or account name plus the associated password. While this is the de facto method used to log in with web consoles and local CLIs, this is the least secure of all authentication methods and _never_ something you want to share with other members of your team or organization or use to authenticate automated workloads. In fact, cloud platforms don't even allow using user account passwords directly as a credential when authenticating to the cloud platform APIs. There is always a process in place that allows exchanging the account/password credential for [another form of long-lived credential](best-security-practices.md#long-lived-credentials-api-keys-account-keys). Even when passwords are mentioned as credentials, some services (e.g. DockerHub) also allow using an API access key in place of the user account password. ## Implicit authentication {% hint style="info" %} The key takeaway here is that implicit authentication gives you immediate access to some cloud resources and requires no configuration, but it may take some extra effort to expand the range of resources that you're initially allowed to access with it. This is not an authentication method you want to use if you're interested in portability and enabling others to reproduce your results. {% endhint %} {% hint style="warning" %} This method may constitute a security risk, because it can give users access to the same cloud resources and services that the ZenML Server itself is configured to access. For this reason, all implicit authentication methods are disabled by default and need to be explicitly enabled by setting the `ZENML_ENABLE_IMPLICIT_AUTH_METHODS` environment variable or the helm chart `enableImplicitAuthMethods` configuration option to `true` in the ZenML deployment. {% endhint %} Implicit authentication is just a fancy way of saying that the Service Connector will use locally stored credentials, configuration files, environment variables, and basically any form of authentication available in the environment where it is running, either locally or in the cloud. Most cloud providers and their associated Service Connector Types include some form of implicit authentication that is able to automatically discover and use the following forms of authentication in the environment where they are running: * configuration and credentials set up and stored locally through the cloud platform CLI * configuration and credentials passed as environment variables * some form of implicit authentication attached to the workload environment itself. This is only available in virtual environments that are already running inside the same cloud where other resources are available for use. This is called differently depending on the cloud provider in question, but they are essentially the same thing: * in AWS, if you're running on Amazon EC2, ECS, EKS, Lambda, or some other form of AWS cloud workload, credentials can be loaded directly from _the instance metadata service._ This [uses the IAM role attached to your workload](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) to authenticate to other AWS services without the need to configure explicit credentials. * in GCP, a similar _metadata service_ allows accessing other GCP cloud resources via [the service account attached to the GCP workload](https://cloud.google.com/docs/authentication/application-default-credentials#attached-sa) (e.g. GCP VMs or GKE clusters). * in Azure, the [Azure Managed Identity](https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview) services can be used to gain access to other Azure services without requiring explicit credentials There are a few caveats that you should be aware of when choosing an implicit authentication method. It may seem like the easiest way out, but it carries with it some implications that may impact portability and usability later down the road: * when used with a local ZenML deployment, like the default deployment, or [a local ZenML server started with `zenml login --local`](../../../user-guide/production-guide/README.md), the implicit authentication method will use the configuration files and credentials or environment variables set up _on your local machine_. These will not be available to anyone else outside your local environment and will also not be accessible to workloads running in other environments on your local host. This includes for example local K3D Kubernetes clusters and local Docker containers. * when used with a remote ZenML server, the implicit authentication method only works if your ZenML server is deployed in the same cloud as the one supported by the Service Connector Type that you are using. For instance, if you're using the AWS Service Connector Type, then the ZenML server must also be deployed in AWS (e.g. in an EKS Kubernetes cluster). You may also need to manually adjust the cloud configuration of the remote cloud workload where the ZenML server is running to allow access to resources (e.g. add permissions to the AWS IAM role attached to the EC2 or EKS node, add roles to the GCP service account attached to the GKE cluster nodes).
GCP implicit authentication method example The following is an example of using the GCP Service Connector's implicit authentication method to gain immediate access to all the GCP resources that the ZenML server also has access to. Note that this is only possible because the ZenML server is also deployed in GCP, in a GKE cluster, and the cluster is attached to a GCP service account with permissions to access the project resources: ```sh zenml service-connector register gcp-implicit --type gcp --auth-method implicit --project_id=zenml-core ``` {% code title="Example Command Output" %} ```text Successfully registered service connector `gcp-implicit` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 📦 gcs-bucket │ gs://annotation-gcp-store ┃ ┃ │ 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 ┃ ┃ │ gs://zenml-project-time-series-bucket ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ gcr.io/zenml-core ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
### Long-lived credentials (API keys, account keys) {% hint style="success" %} This is the magic formula of authentication methods. When paired with another ability, such as [automatically generating short-lived API tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials), or [impersonating accounts or assuming roles](best-security-practices.md#impersonating-accounts-and-assuming-roles), this is the ideal authentication mechanism to use, particularly when using ZenML in production and when sharing results with other members of your ZenML team. {% endhint %} As a general best practice, but implemented particularly well for cloud platforms, account passwords are never directly used as a credential when authenticating to the cloud platform APIs. There is always a process in place that exchanges the account/password credential for another type of long-lived credential: * AWS uses the [`aws configure` CLI command](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) * GCP offers [the `gcloud auth application-default login` CLI commands](https://cloud.google.com/docs/authentication/provide-credentials-adc#how\_to\_provide\_credentials\_to\_adc) * Azure provides [the `az login` CLI command](https://learn.microsoft.com/en-us/cli/azure/authenticate-azure-cli) None of your original login information is stored on your local machine or used to access workloads. Instead, an API key, account key or some other form of intermediate credential is generated and stored on the local host and used to authenticate to remote cloud service APIs. {% hint style="info" %} When using auto-configuration with Service Connector registration, this is usually the type of credentials automatically identified and extracted from your local machine. {% endhint %} Different cloud providers use different names for these types of long-lived credentials, but they usually represent the same concept, with minor variations regarding the identity information and level of permissions attached to them: * AWS has [Account Access Keys](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-appendix-sign-up.html) and [IAM User Access Keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/id\_credentials\_access-keys.html) * GCP has [User Account Credentials](https://cloud.google.com/docs/authentication#user-accounts) and [Service Account Credentials](https://cloud.google.com/docs/authentication#service-accounts) Generally speaking, a differentiation is being made between the following two classes of credentials: * _user credentials_: credentials representing a human user and usually directly tied to a user account identity. These credentials are usually associated with a broad spectrum of permissions and it is therefore not recommended to share them or make them available outside the confines of your local host. * _service credentials:_ credentials used with automated processes and programmatic access, where humans are not directly involved. These credentials are not directly tied to a user account identity, but some other form of accounting like a service account or an IAM user devised to be used by non-human actors. It is also usually possible to restrict the range of permissions associated with this class of credentials, which makes them better candidates for sharing them with a larger audience. ZenML cloud provider Service Connectors can use both classes of credentials, but you should aim to use _service credentials_ as often as possible instead of _user credentials_, especially in production environments. Attaching automated workloads like ML pipelines to service accounts instead of user accounts acts as an extra layer of protection for your user identity and facilitates enforcing another security best practice called [_"the least-privilege principle"_](https://en.wikipedia.org/wiki/Principle\_of\_least\_privilege)_:_ granting each actor only the minimum level of permissions required to function correctly. Using long-lived credentials on their own still isn't ideal, because if leaked, they pose a security risk, even when they have limited permissions attached. The good news is that ZenML Service Connectors include additional mechanisms that, when used in combination with long-lived credentials, make it even safer to share long-lived credentials with other ZenML users and automated workloads: * automatically [generating temporary credentials](best-security-practices.md#generating-temporary-and-down-scoped-credentials) from long-lived credentials and even downgrading their permission scope to enforce the least-privilege principle * implementing [authentication schemes that impersonate accounts and assume roles](best-security-practices.md#impersonating-accounts-and-assuming-roles) ### Generating temporary and down-scoped credentials Most [authentication methods that utilize long-lived credentials](best-security-practices.md#long-lived-credentials-api-keys-account-keys) also implement additional mechanisms that help reduce the accidental credentials exposure and risk of security incidents even further, making them ideal for production. _**Issuing temporary credentials**_: this authentication strategy keeps long-lived credentials safely stored on the ZenML server and away from the eyes of actual API clients and people that need to authenticate to the remote resources. Instead, clients are issued API tokens that have a limited lifetime and expire after a given amount of time. The Service Connector is able to generate these API tokens from long-lived credentials on a need-to-have basis. For example, the AWS Service Connector's "Session Token", "Federation Token" and "IAM Role" authentication methods and basically all authentication methods supported by the GCP Service Connector support this feature.
AWS temporary credentials example The following example shows the difference between the long-lived AWS credentials configured for an AWS Service Connector and kept on the ZenML server and the temporary Kubernetes API token credentials that the client receives and uses to access the resource. First, showing the long-lived AWS credentials configured for the AWS Service Connector: ```sh zenml service-connector describe eks-zenhacks-cluster ``` {% code title="Example Command Output" %} ```text Service connector 'eks-zenhacks-cluster' of type 'aws' with id 'be53166a-b39c-4e39-8e31-84658e50eec4' is owned by user 'default' and is 'private'. 'eks-zenhacks-cluster' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ ID │ be53166a-b39c-4e39-8e31-84658e50eec4 ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ NAME │ eks-zenhacks-cluster ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ AUTH METHOD │ session-token ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🌀 kubernetes-cluster ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ RESOURCE NAME │ zenhacks-cluster ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SECRET ID │ fa42ab38-3c93-4765-a4c6-9ce0b548a86c ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SESSION DURATION │ 43200s ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-16 10:15:26.393769 ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-16 10:15:26.393772 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %} Then, showing the temporary credentials that are issued to clients. Note the expiration time on the Kubernetes API token: ```sh zenml service-connector describe eks-zenhacks-cluster --client ``` {% code title="Example Command Output" %} ```text Service connector 'eks-zenhacks-cluster (kubernetes-cluster | zenhacks-cluster client)' of type 'kubernetes' with id 'be53166a-b39c-4e39-8e31-84658e50eec4' is owned by user 'default' and is 'private'. 'eks-zenhacks-cluster (kubernetes-cluster | zenhacks-cluster client)' kubernetes Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ ID │ be53166a-b39c-4e39-8e31-84658e50eec4 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ NAME │ eks-zenhacks-cluster (kubernetes-cluster | zenhacks-cluster client) ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🌀 kubernetes ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ token ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🌀 kubernetes-cluster ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ arn:aws:eks:us-east-1:715803424590:cluster/zenhacks-cluster ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ 11h59m57s ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-16 10:17:46.931091 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-16 10:17:46.931094 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ server │ https://A5F8F4142FB12DDCDE9F21F6E9B07A18.gr7.us-east-1.eks.amazonaws.com ┃ ┠───────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ insecure │ False ┃ ┠───────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ cluster_name │ arn:aws:eks:us-east-1:715803424590:cluster/zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ token │ [HIDDEN] ┃ ┠───────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ certificate_authority │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
_**Issuing downscoped credentials**_: in addition to the above, some authentication methods also support restricting the generated temporary API tokens to the minimum set of permissions required to access the target resource or set of resources. This is currently available for the AWS Service Connector's "Federation Token" and "IAM Role" authentication methods.
AWS down-scoped credentials example It's not easy to showcase this without using some ZenML Python Client code, but here is an example that proves that the AWS client token issued to an S3 client can only access the S3 bucket resource it was issued for, even if the originating AWS Service Connector is able to access multiple S3 buckets with the corresponding long-lived credentials: ```sh zenml service-connector register aws-federation-multi --type aws --auth-method=federation-token --auto-configure ``` {% code title="Example Command Output" %} ```text Successfully registered service connector `aws-federation-multi` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┃ │ s3://zenml-public-datasets ┃ ┃ │ s3://zenml-public-swagger-spec ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The next part involves running some ZenML Python code to showcase that the downscoped credentials issued to a client are indeed restricted to the S3 bucket that the client asked to access: ```python from zenml.client import Client client = Client() # Get a Service Connector client for a particular S3 bucket connector_client = client.get_service_connector_client( name_id_or_prefix="aws-federation-multi", resource_type="s3-bucket", resource_id="s3://zenfiles" ) # Get the S3 boto3 python client pre-configured and pre-authenticated # from the Service Connector client s3_client = connector_client.connect() # Verify access to the chosen S3 bucket using the temporary token that # was issued to the client. s3_client.head_bucket(Bucket="zenfiles") # Try to access another S3 bucket that the original AWS long-lived credentials can access. # An error will be thrown indicating that the bucket is not accessible. s3_client.head_bucket(Bucket="zenml-demos") ``` {% code title="Example Output" %} ```text >>> from zenml.client import Client >>> >>> client = Client() Unable to find ZenML repository in your current working directory (/home/stefan/aspyre/src/zenml) or any parent directories. If you want to use an existing repository which is in a different location, set the environment variable 'ZENML_REPOSITORY_PATH'. If you want to create a new repository, run zenml init. Running without an active repository root. >>> >>> # Get a Service Connector client for a particular S3 bucket >>> connector_client = client.get_service_connector_client( ... name_id_or_prefix="aws-federation-multi", ... resource_type="s3-bucket", ... resource_id="s3://zenfiles" ... ) >>> >>> # Get the S3 boto3 python client pre-configured and pre-authenticated >>> # from the Service Connector client >>> s3_client = connector_client.connect() >>> >>> # Verify access to the chosen S3 bucket using the temporary token that >>> # was issued to the client. >>> s3_client.head_bucket(Bucket="zenfiles") {'ResponseMetadata': {'RequestId': '62YRYW5XJ1VYPCJ0', 'HostId': 'YNBXcGUMSOh90AsTgPW6/Ra89mqzfN/arQq/FMcJzYCK98cFx53+9LLfAKzZaLhwaiJTm+s3mnU=', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': 'YNBXcGUMSOh90AsTgPW6/Ra89mqzfN/arQq/FMcJzYCK98cFx53+9LLfAKzZaLhwaiJTm+s3mnU=', 'x-amz-request-id': '62YRYW5XJ1VYPCJ0', 'date': 'Fri, 16 Jun 2023 11:04:20 GMT', 'x-amz-bucket-region': 'us-east-1', 'x-amz-access-point-alias': 'false', 'content-type': 'application/xml', 'server': 'AmazonS3'}, 'RetryAttempts': 0}} >>> >>> # Try to access another S3 bucket that the original AWS long-lived credentials can access. >>> # An error will be thrown indicating that the bucket is not accessible. >>> s3_client.head_bucket(Bucket="zenml-demos") ╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮ │ :1 in │ │ │ │ /home/stefan/aspyre/src/zenml/.venv/lib/python3.8/site-packages/botocore/client.py:508 in │ │ _api_call │ │ │ │ 505 │ │ │ │ │ f"{py_operation_name}() only accepts keyword arguments." │ │ 506 │ │ │ │ ) │ │ 507 │ │ │ # The "self" in this scope is referring to the BaseClient. │ │ ❱ 508 │ │ │ return self._make_api_call(operation_name, kwargs) │ │ 509 │ │ │ │ 510 │ │ _api_call.__name__ = str(py_operation_name) │ │ 511 │ │ │ │ /home/stefan/aspyre/src/zenml/.venv/lib/python3.8/site-packages/botocore/client.py:915 in │ │ _make_api_call │ │ │ │ 912 │ │ if http.status_code >= 300: │ │ 913 │ │ │ error_code = parsed_response.get("Error", {}).get("Code") │ │ 914 │ │ │ error_class = self.exceptions.from_code(error_code) │ │ ❱ 915 │ │ │ raise error_class(parsed_response, operation_name) │ │ 916 │ │ else: │ │ 917 │ │ │ return parsed_response │ │ 918 │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯ ClientError: An error occurred (403) when calling the HeadBucket operation: Forbidden ``` {% endcode %}
### Impersonating accounts and assuming roles {% hint style="success" %} These types of authentication methods require more work to set up because multiple permission-bearing accounts and roles need to be provisioned in advance depending on the target audience. On the other hand, they also provide the most flexibility and control. Despite their operational cost, if you are a platform engineer and have the infrastructure know-how necessary to understand and set up the authentication resources, this is for you. {% endhint %} These authentication methods deliver another way of [configuring long-lived credentials](best-security-practices.md#long-lived-credentials-api-keys-account-keys) in your Service Connectors without exposing them to clients. They are especially useful as an alternative to cloud provider Service Connectors authentication methods that do not support [automatically downscoping the permissions of issued temporary tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials). The processes of account impersonation and role assumption are very similar and can be summarized as follows: * you configure a Service Connector with long-lived credentials associated with a primary user account or primary service account (preferable). As a best practice, it is common to attach a reduced set of permissions or even no permissions to these credentials other than those that allow the account impersonation or role assumption operation. This makes it more difficult to do any damage if the primary credentials are accidentally leaked. * in addition to the primary account and its long-lived credentials, you also need to provision one or more secondary access entities in the cloud platform bearing the effective permissions that will be needed to access the target resource(s): * one or more IAM roles (to be assumed) * one or more service accounts (to be impersonated) * the Service Connector configuration also needs to contain the name of a target IAM role to be assumed or a service account to be impersonated. * upon request, the Service Connector will exchange the long-lived credentials associated with the primary account for short-lived API tokens that only have the permissions associated with the target IAM role or service account. These temporary credentials are issued to clients and used to access the target resource, while the long-lived credentials are kept safe and never have to leave the ZenML server boundary.
GCP account impersonation example For this example, we have the following set up in GCP: * a primary `empty-connectors@zenml-core.iam.gserviceaccount.com` GCP service account with no permissions whatsoever aside from the "Service Account Token Creator" role that allows it to impersonate the secondary service account below. We also generate a service account key for this account. * a secondary `zenml-bucket-sl@zenml-core.iam.gserviceaccount.com` GCP service account that only has permissions to access the `zenml-bucket-sl` GCS bucket First, let's show that the `empty-connectors` service account has no permissions to access any GCS buckets or any other resources for that matter. We'll register a regular GCP Service Connector that uses the service account key (long-lived credentials) directly: ```sh zenml service-connector register gcp-empty-sa --type gcp --auth-method service-account --service_account_json=@empty-connectors@zenml-core.json --project_id=zenml-core ``` {% code title="Example Command Output" %} ```text Expanding argument value service_account_json to contents of file /home/stefan/aspyre/src/zenml/empty-connectors@zenml-core.json. Successfully registered service connector `gcp-empty-sa` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┠───────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 📦 gcs-bucket │ 💥 error: connector authorization failure: failed to list GCS buckets: 403 GET ┃ ┃ │ https://storage.googleapis.com/storage/v1/b?project=zenml-core&projection=noAcl&prettyPrint= ┃ ┃ │ false: empty-connectors@zenml-core.iam.gserviceaccount.com does not have ┃ ┃ │ storage.buckets.list access to the Google Cloud project. Permission 'storage.buckets.list' ┃ ┃ │ denied on resource (or it may not exist). ┃ ┠───────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ 💥 error: connector authorization failure: Failed to list GKE clusters: 403 Required ┃ ┃ │ "container.clusters.list" permission(s) for "projects/20219041791". [request_id: ┃ ┃ │ "0xcb7086235111968a" ┃ ┃ │ ] ┃ ┠───────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ gcr.io/zenml-core ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} Next, we'll register a GCP Service Connector that actually uses account impersonation to access the `zenml-bucket-sl` GCS bucket and verify that it can actually access the bucket: ```sh zenml service-connector register gcp-impersonate-sa --type gcp --auth-method impersonation --service_account_json=@empty-connectors@zenml-core.json --project_id=zenml-core --target_principal=zenml-bucket-sl@zenml-core.iam.gserviceaccount.com --resource-type gcs-bucket --resource-id gs://zenml-bucket-sl ``` {% code title="Example Command Output" %} ```text Expanding argument value service_account_json to contents of file /home/stefan/aspyre/src/zenml/empty-connectors@zenml-core.json. Successfully registered service connector `gcp-impersonate-sa` with access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼──────────────────────┨ ┃ 📦 gcs-bucket │ gs://zenml-bucket-sl ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
### Short-lived credentials {% hint style="info" %} This category of authentication methods uses temporary credentials explicitly configured in the Service Connector or generated by the Service Connector during auto-configuration. Of all available authentication methods, this is probably the least useful and you will likely never have to use it because it is terribly impractical: when short-lived credentials expire, Service Connectors become unusable and need to either be manually updated or replaced. On the other hand, this authentication method is ideal if you're looking to grant someone else in your team temporary access to some resources without exposing your long-lived credentials. {% endhint %} A previous section described how [temporary credentials can be automatically generated from other, long-lived credentials](best-security-practices.md#generating-temporary-and-down-scoped-credentials) by most cloud provider Service Connectors. It only stands to reason that temporary credentials can also be generated manually by external means such as cloud provider CLIs and used directly to configure Service Connectors, or automatically generated during Service Connector auto-configuration. This may be used as a way to grant an external party temporary access to some resources and have the Service Connector automatically become unusable (i.e. expire) after some time. Your long-lived credentials are kept safe, while the Service Connector only stores a short-lived credential.
AWS short-lived credentials auto-configuration example The following is an example of using Service Connector auto-configuration to automatically generate a short-lived token from long-lived credentials configured for the local cloud provider CLI (AWS in this case): ```sh AWS_PROFILE=connectors zenml service-connector register aws-sts-token --type aws --auto-configure --auth-method sts-token ``` {% code title="Example Command Output" %} ```text ⠸ Registering service connector 'aws-sts-token'... Successfully registered service connector `aws-sts-token` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┃ │ s3://zenml-public-datasets ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The Service Connector is now configured with a short-lived token that will expire after some time. You can verify this by inspecting the Service Connector: ```sh zenml service-connector describe aws-sts-token ``` {% code title="Example Command Output" %} ```text Service connector 'aws-sts-token' of type 'aws' with id '63e14350-6719-4255-b3f5-0539c8f7c303' is owned by user 'default' and is 'private'. 'aws-sts-token' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ ID │ e316bcb3-6659-467b-81e5-5ec25bfd36b0 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ aws-sts-token ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ sts-token ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔶 aws-generic, 📦 s3-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ 971318c9-8db9-4297-967d-80cda070a121 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ 11h58m17s ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-19 17:58:42.999323 ┃ ┠──────────────────┼─────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-19 17:58:42.999324 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_session_token │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %} Note the temporary nature of the Service Connector. It will become unusable in 12 hours: ```sh zenml service-connector list --name aws-sts-token ``` {% code title="Example Command Output" %} ```text ┏━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼───────────────┼─────────────────────────────────┼────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ aws-sts-token │ e316bcb3-6659-467b-81e5-5ec25bf │ 🔶 aws │ 🔶 aws-generic │ │ ➖ │ default │ 11h57m12s │ ┃ ┃ │ │ d36b0 │ │ 📦 s3-bucket │ │ │ │ │ ┃ ┃ │ │ │ │ 🌀 kubernetes-cluster │ │ │ │ │ ┃ ┃ │ │ │ │ 🐳 docker-registry │ │ │ │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┛ ``` {% endcode %}
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/auth-management/docker-service-connector.md ================ --- description: Configuring Docker Service Connectors to connect ZenML to Docker container registries. --- # Docker Service Connector The ZenML Docker Service Connector allows authenticating with a Docker or OCI container registry and managing Docker clients for the registry. This connector provides pre-authenticated python-docker Python clients to Stack Components that are linked to it. ```shell zenml service-connector list-types --type docker ``` ```shell ┏━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ NAME │ TYPE │ RESOURCE TYPES │ AUTH METHODS │ LOCAL │ REMOTE ┃ ┠──────────────────────────┼───────────┼────────────────────┼──────────────┼───────┼────────┨ ┃ Docker Service Connector │ 🐳 docker │ 🐳 docker-registry │ password │ ✅ │ ✅ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` ## Prerequisites No Python packages are required for this Service Connector. All prerequisites are included in the base ZenML Python package. Docker needs to be installed on environments where container images are built and pushed to the target container registry. ## Resource Types The Docker Service Connector only supports authenticating to and granting access to a Docker/OCI container registry. This type of resource is identified by the `docker-registry` Resource Type. The resource name identifies a Docker/OCI registry using one of the following formats (the repository name is optional and ignored). * DockerHub: docker.io or `https://index.docker.io/v1/` * generic OCI registry URI: `https://host:port/` ## Authentication Methods Authenticating to Docker/OCI container registries is done with a username and password or access token. It is recommended to use API tokens instead of passwords, wherever this is available, for example in the case of DockerHub: ```sh zenml service-connector register dockerhub --type docker -in ``` {% code title="Example Command Output" %} ```text Please enter a name for the service connector [dockerhub]: Please enter a description for the service connector []: Please select a service connector type (docker) [docker]: Only one resource type is available for this connector (docker-registry). Only one authentication method is available for this connector (password). Would you like to use it? [Y/n]: Please enter the configuration for the Docker username and password/token authentication method. [username] Username {string, secret, required}: [password] Password {string, secret, required}: [registry] Registry server URL. Omit to use DockerHub. {string, optional}: Successfully registered service connector `dockerhub` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠────────────────────┼────────────────┨ ┃ 🐳 docker-registry │ docker.io ┃ ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} {% hint style="warning" %} This Service Connector does not support generating short-lived credentials from the username and password or token credentials configured in the Service Connector. In effect, this means that the configured credentials will be distributed directly to clients and used to authenticate directly to the target Docker/OCI registry service. {% endhint %} ## Auto-configuration {% hint style="info" %} This Service Connector does not support auto-discovery and extraction of authentication credentials from local Docker clients. If this feature is useful to you or your organization, please let us know by messaging us in [Slack](https://zenml.io/slack) or [creating an issue on GitHub](https://github.com/zenml-io/zenml/issues). {% endhint %} ## Local client provisioning This Service Connector allows configuring the local Docker client with credentials: ```sh zenml service-connector login dockerhub ``` {% code title="Example Command Output" %} ```text 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 %} ## Stack Components use The Docker Service Connector can be used by all Container Registry stack component flavors to authenticate to a remote Docker/OCI container registry. This allows container images to be built and published to private container registries without the need to configure explicit Docker credentials in the target environment or the Stack Component. {% hint style="warning" %} ZenML does not yet support automatically configuring Docker credentials in container runtimes such as Kubernetes clusters (i.e. via imagePullSecrets) to allow container images to be pulled from the private container registries. This will be added in a future release. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/auth-management/gcp-service-connector.md ================ --- description: >- Configuring GCP Service Connectors to connect ZenML to GCP resources such as GCS buckets, GKE Kubernetes clusters, and GCR container registries. --- # GCP Service Connector The ZenML GCP Service Connector facilitates the authentication and access to managed GCP services and resources. These encompass a range of resources, including GCS buckets, GAR and GCR container repositories, and GKE clusters. The connector provides support for various authentication methods, including GCP user accounts, service accounts, short-lived OAuth 2.0 tokens, and implicit authentication. To ensure heightened security measures, this connector always issues [short-lived OAuth 2.0 tokens to clients instead of long-lived credentials](best-security-practices.md#generating-temporary-and-down-scoped-credentials) unless explicitly configured to do otherwise. Furthermore, it includes [automatic configuration and detection of credentials locally configured through the GCP CLI](service-connectors-guide.md#auto-configuration). This connector serves as a general means of accessing any GCP service by issuing OAuth 2.0 credential objects to clients. Additionally, the connector can handle specialized authentication for GCS, Docker, and Kubernetes Python clients. It also allows for the configuration of local Docker and Kubernetes CLIs. ```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 │ external-account │ │ ┃ ┃ │ │ │ oauth2-token │ │ ┃ ┃ │ │ │ impersonation │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` ## Prerequisites The GCP Service Connector is part of the GCP ZenML integration. You can either install the entire integration or use a PyPI extra to install it independently of the integration: * `pip install "zenml[connectors-gcp]"` installs only prerequisites for the GCP Service Connector Type * `zenml integration install gcp` installs the entire GCP ZenML integration It is not required to [install and set up the GCP CLI on your local machine](https://cloud.google.com/sdk/gcloud) to use the GCP Service Connector to link Stack Components to GCP resources and services. However, it is recommended to do so if you are looking for a quick setup that includes using the auto-configuration Service Connector features. {% hint style="info" %} The auto-configuration examples in this page rely on the GCP CLI being installed and already configured with valid credentials of one type or another. If you want to avoid installing the GCP CLI, we recommend using the interactive mode of the ZenML CLI to register Service Connectors: ``` zenml service-connector register -i --type gcp ``` {% endhint %} ## Resource Types ### Generic GCP resource This resource type allows Stack Components to use the GCP Service Connector to connect to any GCP service or resource. When used by Stack Components, they are provided a Python google-auth credentials object populated with a GCP OAuth 2.0 token. This credentials object can then be used to create GCP Python clients for any particular GCP service. This generic GCP resource type is meant to be used with Stack Components that are not represented by one of the other, more specific resource types like GCS buckets, Kubernetes clusters, or Docker registries. For example, it can be used with [the Google Cloud Image Builder](../../../component-guide/image-builders/gcp.md) stack component, or [the Vertex AI Orchestrator](../../../component-guide/orchestrators/vertex.md) and [Step Operator](../../../component-guide/step-operators/vertex.md). It should be accompanied by a matching set of GCP permissions that allow access to the set of remote resources required by the client and Stack Component (see the documentation of each Stack Component for more details). The resource name represents the GCP project that the connector is authorized to access. ### GCS bucket Allows Stack Components to connect to GCS buckets. When used by Stack Components, they are provided a pre-configured GCS Python client instance. The configured credentials must have at least the following [GCP permissions](https://cloud.google.com/iam/docs/permissions-reference) associated with the GCS buckets that it can access: * `storage.buckets.list` * `storage.buckets.get` * `storage.objects.create` * `storage.objects.delete` * `storage.objects.get` * `storage.objects.list` * `storage.objects.update` For example, the GCP Storage Admin role includes all of the required permissions, but it also includes additional permissions that are not required by the connector. If set, the resource name must identify a GCS bucket using one of the following formats: * GCS bucket URI (canonical resource name): gs://{bucket-name} * GCS bucket name: {bucket-name} ### GKE Kubernetes cluster Allows Stack Components to access a GKE cluster as a standard Kubernetes cluster resource. When used by Stack Components, they are provided a pre-authenticated Python Kubernetes client instance. The configured credentials must have at least the following [GCP permissions](https://cloud.google.com/iam/docs/permissions-reference) associated with the GKE clusters that it can access: * `container.clusters.list` * `container.clusters.get` In addition to the above permissions, the credentials should include permissions to connect to and use the GKE cluster (i.e. some or all permissions in the Kubernetes Engine Developer role). If set, the resource name must identify a GKE cluster using one of the following formats: * GKE cluster name: `{cluster-name}` GKE cluster names are project scoped. The connector can only be used to access GKE clusters in the GCP project that it is configured to use. ### GAR container registry (including legacy GCR support) {% 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.". Support for legacy GCR registries is still included in the GCP service connector. Users that already have GCP service connectors configured to access GCR registries may continue to use them without taking any action. However, it is recommended to transition to Google Artifact Registries as soon as possible by following [the GCP guide on this subject](https://cloud.google.com/artifact-registry/docs/transition/transition-from-gcr) and making the following updates to ZenML GCP Service Connectors that are used to access GCR resources: * add the IAM permissions documented here to the GCP Service Connector credentials to enable them to access the Artifact Registries. * users may keep the gcr.io GCR URLs already configured in the GCP Service Connectors as well as those used in linked Container Registry stack components given that these domains are redirected by Google to GAR as covered in the GCR transition guide. Alternatively, users may update the GCP Service Connector configuration and/or the Container Registry stack components to use the replacement Artifact Registry URLs. The GCP Service Connector will list the legacy GCR registries as accessible for a GCP project even if the GCP Service Connector credentials do not grant access to GCR registries. This is required for backwards-compatibility and will be removed in a future release. {% endhint %} Allows Stack Components to access a Google Artifact Registry as a standard Docker registry resource. When used by Stack Components, they are provided a pre-authenticated Python Docker client instance. The configured credentials must have at least the following [GCP permissions](https://cloud.google.com/iam/docs/understanding-roles#artifact-registry-roles): * `artifactregistry.repositories.createOnPush` * `artifactregistry.repositories.downloadArtifacts` * `artifactregistry.repositories.get` * `artifactregistry.repositories.list` * `artifactregistry.repositories.readViaVirtualRepository` * `artifactregistry.repositories.uploadArtifacts` * `artifactregistry.locations.list` The Artifact Registry Create-on-Push Writer role includes all of the above permissions. This resource type also includes legacy GCR container registry support. When used with GCR registries, the configured credentials must have at least the following [GCP permissions](https://cloud.google.com/iam/docs/understanding-roles#cloud-storage-roles): * `storage.buckets.get` * `storage.multipartUploads.abort` * `storage.multipartUploads.create` * `storage.multipartUploads.list` * `storage.multipartUploads.listParts` * `storage.objects.create` * `storage.objects.delete` * `storage.objects.list` The Storage Legacy Bucket Writer role includes all of the above permissions while at the same time restricting access to only the GCR buckets. If set, the resource name must identify a GAR or GCR registry using one of the following formats: * Google Artifact Registry repository URI: `[https://]-docker.pkg.dev//[/]` * Google Artifact Registry name: `projects//locations//repositories/` * (legacy) GCR repository URI: `[https://][us.|eu.|asia.]gcr.io/[/]` The connector can only be used to access GAR and GCR registries in the GCP project that it is configured to use. ## Authentication Methods ### Implicit authentication [Implicit authentication](best-security-practices.md#implicit-authentication) to GCP services using [Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc). {% hint style="warning" %} This method may constitute a security risk, because it can give users access to the same cloud resources and services that the ZenML Server itself is configured to access. For this reason, all implicit authentication methods are disabled by default and need to be explicitly enabled by setting the `ZENML_ENABLE_IMPLICIT_AUTH_METHODS` environment variable or the helm chart `enableImplicitAuthMethods` configuration option to `true` in the ZenML deployment. {% endhint %} This authentication method doesn't require any credentials to be explicitly configured. It automatically discovers and uses credentials from one of the following sources: * environment variables (GOOGLE\_APPLICATION\_CREDENTIALS) * local ADC credential files set up by running `gcloud auth application-default login` (e.g. `~/.config/gcloud/application_default_credentials.json`). * a GCP service account attached to the resource where the ZenML server is running. Only works when running the ZenML server on a GCP resource with a service account attached to it or when using Workload Identity (e.g. GKE cluster). This is the quickest and easiest way to authenticate to GCP services. However, the results depend on how ZenML is deployed and the environment where it is used and is thus not fully reproducible: * when used with the default local ZenML deployment or a local ZenML server, the credentials are those set up on your machine (i.e. by running `gcloud auth application-default login` or setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to point to a service account key JSON file). * when connected to a ZenML server, this method only works if the ZenML server is deployed in GCP and will use the service account attached to the GCP resource where the ZenML server is running (e.g. a GKE cluster). The service account permissions may need to be adjusted to allow listing and accessing/describing the GCP resources that the connector is configured to access. Note that the discovered credentials inherit the full set of permissions of the local GCP CLI credentials or service account attached to the ZenML server GCP workload. Depending on the extent of those permissions, this authentication method might not be suitable for production use, as it can lead to accidental privilege escalation. Instead, it is recommended to use [the Service Account Key](gcp-service-connector.md#gcp-service-account) or [Service Account Impersonation](gcp-service-connector.md#gcp-service-account-impersonation) authentication methods to restrict the permissions that are granted to the connector clients. To find out more about Application Default Credentials, [see the GCP ADC documentation](https://cloud.google.com/docs/authentication/provide-credentials-adc). A GCP project is required and the connector may only be used to access GCP resources in the specified project. When used remotely in a GCP workload, the configured project has to be the same as the project of the attached service account.
Example configuration The following assumes the local GCP CLI has already been configured with user account credentials by running the `gcloud auth application-default login` command: ```sh zenml service-connector register gcp-implicit --type gcp --auth-method implicit --auto-configure ``` {% code title="Example Command Output" %} ``` Successfully registered service connector `gcp-implicit` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 📦 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 ┃ ┃ │ gs://zenml-project-time-series-bucket ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🐳 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 %} No credentials are stored with the Service Connector: ```sh zenml service-connector describe gcp-implicit ``` {% code title="Example Command Output" %} ``` Service connector 'gcp-implicit' of type 'gcp' with id '0c49a7fe-5e87-41b9-adbe-3da0a0452e44' is owned by user 'default' and is 'private'. 'gcp-implicit' gcp Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ ID │ 0c49a7fe-5e87-41b9-adbe-3da0a0452e44 ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ gcp-implicit ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔵 gcp ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ implicit ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔵 gcp-generic, 📦 gcs-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-05-19 08:04:51.037955 ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-05-19 08:04:51.037958 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━┯━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠────────────┼────────────┨ ┃ project_id │ zenml-core ┃ ┗━━━━━━━━━━━━┷━━━━━━━━━━━━┛ ``` {% endcode %}
### GCP User Account [Long-lived GCP credentials](best-security-practices.md#long-lived-credentials-api-keys-account-keys) consist of a GCP user account and its credentials. This method requires GCP user account credentials like those generated by the `gcloud auth application-default login` command. By default, the GCP connector [generates temporary OAuth 2.0 tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials) from the user account credentials and distributes them to clients. The tokens have a limited lifetime of 1 hour. This behavior can be disabled by setting the `generate_temporary_tokens` configuration option to `False`, in which case, the connector will distribute the user account credentials JSON to clients instead (not recommended). This method is preferred during development and testing due to its simplicity and ease of use. It is not recommended as a direct authentication method for production use cases because the clients are granted the full set of permissions of the GCP user account. For production, it is recommended to use the GCP Service Account or GCP Service Account Impersonation authentication methods. A GCP project is required and the connector may only be used to access GCP resources in the specified project. If you already have the local GCP CLI set up with these credentials, they will be automatically picked up when auto-configuration is used (see the example below).
Example auto-configuration The following assumes the local GCP CLI has been configured with GCP user account credentials by running the `gcloud auth application-default login` command: ```sh zenml service-connector register gcp-user-account --type gcp --auth-method user-account --auto-configure ``` {% code title="Example Command Output" %} ``` Successfully registered service connector `gcp-user-account` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 📦 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 ┃ ┃ │ gs://zenml-project-time-series-bucket ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🐳 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 %} The GCP user account credentials were lifted up from the local host: ```sh zenml service-connector describe gcp-user-account ``` {% code title="Example Command Output" %} ``` Service connector 'gcp-user-account' of type 'gcp' with id 'ddbce93f-df14-4861-a8a4-99a80972f3bc' is owned by user 'default' and is 'private'. 'gcp-user-account' gcp Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ ID │ ddbce93f-df14-4861-a8a4-99a80972f3bc ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ gcp-user-account ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔵 gcp ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ user-account ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔵 gcp-generic, 📦 gcs-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ 17692951-614f-404f-a13a-4abb25bfa758 ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-05-19 08:09:44.102934 ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-05-19 08:09:44.102936 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────┼────────────┨ ┃ project_id │ zenml-core ┃ ┠───────────────────┼────────────┨ ┃ user_account_json │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┛ ``` {% endcode %}
### GCP Service Account [Long-lived GCP credentials](best-security-practices.md#long-lived-credentials-api-keys-account-keys) consisting of a GCP service account and its credentials. This method requires [a GCP service account](https://cloud.google.com/iam/docs/service-account-overview) and [a service account key JSON](https://cloud.google.com/iam/docs/service-account-creds#key-types) created for it. By default, the GCP connector [generates temporary OAuth 2.0 tokens](best-security-practices.md#generating-temporary-and-down-scoped-credentials) from the service account credentials and distributes them to clients. The tokens have a limited lifetime of 1 hour. This behavior can be disabled by setting the `generate_temporary_tokens` configuration option to `False`, in which case, the connector will distribute the service account credentials JSON to clients instead (not recommended). A GCP project is required and the connector may only be used to access GCP resources in the specified project. If you already have the `GOOGLE_APPLICATION_CREDENTIALS` environment variable configured to point to a service account key JSON file, it will be automatically picked up when auto-configuration is used.
Example configuration The following assumes a GCP service account was created, [granted permissions to access GCS buckets](gcp-service-connector.md#gcs-bucket) in the target project and a service account key JSON was generated and saved locally in the `connectors-devel@zenml-core.json` file: ```sh zenml service-connector register gcp-service-account --type gcp --auth-method service-account --resource-type gcs-bucket --project_id=zenml-core --service_account_json=@connectors-devel@zenml-core.json ``` {% code title="Example Command Output" %} ``` Expanding argument value service_account_json to contents of file connectors-devel@zenml-core.json. Successfully registered service connector `gcp-service-account` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 📦 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 ┃ ┃ │ gs://zenml-project-time-series-bucket ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The GCP service connector configuration and service account credentials: ```sh zenml service-connector describe gcp-service-account ``` {% code title="Example Command Output" %} ``` Service connector 'gcp-service-account' of type 'gcp' with id '4b3d41c9-6a6f-46da-b7ba-8f374c3f49c5' is owned by user 'default' and is 'private'. 'gcp-service-account' gcp Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ ID │ 4b3d41c9-6a6f-46da-b7ba-8f374c3f49c5 ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ NAME │ gcp-service-account ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ TYPE │ 🔵 gcp ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ AUTH METHOD │ service-account ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ RESOURCE TYPES │ 📦 gcs-bucket ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SECRET ID │ 0d0a42bb-40a4-4f43-af9e-6342eeca3f28 ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ CREATED_AT │ 2023-05-19 08:15:48.056937 ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-05-19 08:15:48.056940 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────────┼────────────┨ ┃ project_id │ zenml-core ┃ ┠──────────────────────┼────────────┨ ┃ service_account_json │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┛ ``` {% endcode %}
### GCP Service Account impersonation Generates [temporary STS credentials](best-security-practices.md#impersonating-accounts-and-assuming-roles) by [impersonating another GCP service account](https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-impersonation). The connector needs to be configured with the email address of the target GCP service account to be impersonated, accompanied by a GCP service account key JSON for the primary service account. The primary service account must have permission to generate tokens for the target service account (i.e. [the Service Account Token Creator role](https://cloud.google.com/iam/docs/service-account-permissions#directly-impersonate)). The connector will generate temporary OAuth 2.0 tokens upon request by using [GCP direct service account impersonation](https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-impersonation). The tokens have a configurable limited lifetime of up to 1 hour. [The best practice implemented with this authentication scheme](best-security-practices.md#impersonating-accounts-and-assuming-roles) is to keep the set of permissions associated with the primary service account down to the bare minimum and grant permissions to the privilege-bearing service account instead. A GCP project is required and the connector may only be used to access GCP resources in the specified project. If you already have the `GOOGLE_APPLICATION_CREDENTIALS` environment variable configured to point to the primary service account key JSON file, it will be automatically picked up when auto-configuration is used.
Configuration example For this example, we have the following set up in GCP: * a primary `empty-connectors@zenml-core.iam.gserviceaccount.com` GCP service account with no permissions whatsoever aside from the "Service Account Token Creator" role that allows it to impersonate the secondary service account below. We also generate a service account key for this account. * a secondary `zenml-bucket-sl@zenml-core.iam.gserviceaccount.com` GCP service account that only has permission to access the `zenml-bucket-sl` GCS bucket First, let's show that the `empty-connectors` service account has no permission to access any GCS buckets or any other resources for that matter. We'll register a regular GCP Service Connector that uses the service account key (long-lived credentials) directly: ```sh zenml service-connector register gcp-empty-sa --type gcp --auth-method service-account --service_account_json=@empty-connectors@zenml-core.json --project_id=zenml-core ``` {% code title="Example Command Output" %} ``` Expanding argument value service_account_json to contents of file /home/stefan/aspyre/src/zenml/empty-connectors@zenml-core.json. Successfully registered service connector `gcp-empty-sa` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┠───────────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 📦 gcs-bucket │ 💥 error: connector authorization failure: failed to list GCS buckets: 403 GET ┃ ┃ │ https://storage.googleapis.com/storage/v1/b?project=zenml-core&projection=noAcl&prettyPrint=false: ┃ ┃ │ empty-connectors@zenml-core.iam.gserviceaccount.com does not have storage.buckets.list access to the Google Cloud ┃ ┃ │ project. Permission 'storage.buckets.list' denied on resource (or it may not exist). ┃ ┠───────────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ 💥 error: connector authorization failure: Failed to list GKE clusters: 403 Required "container.clusters.list" ┃ ┃ │ permission(s) for "projects/20219041791". [request_id: "0x84808facdac08541" ┃ ┃ │ ] ┃ ┠───────────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ gcr.io/zenml-core ┃ ┃ │ us.gcr.io/zenml-core ┃ ┃ │ eu.gcr.io/zenml-core ┃ ┃ │ asia.gcr.io/zenml-core ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} Verifying access to individual resource types will fail: ```sh zenml service-connector verify gcp-empty-sa --resource-type kubernetes-cluster ``` {% code title="Example Command Output" %} ``` Error: Service connector 'gcp-empty-sa' verification failed: connector authorization failure: Failed to list GKE clusters: 403 Required "container.clusters.list" permission(s) for "projects/20219041791". ``` {% endcode %} ```sh zenml service-connector verify gcp-empty-sa --resource-type gcs-bucket ``` {% code title="Example Command Output" %} ``` Error: Service connector 'gcp-empty-sa' verification failed: connector authorization failure: failed to list GCS buckets: 403 GET https://storage.googleapis.com/storage/v1/b?project=zenml-core&projection=noAcl&prettyPrint=false: empty-connectors@zenml-core.iam.gserviceaccount.com does not have storage.buckets.list access to the Google Cloud project. Permission 'storage.buckets.list' denied on resource (or it may not exist). ``` {% endcode %} ```sh zenml service-connector verify gcp-empty-sa --resource-type gcs-bucket --resource-id zenml-bucket-sl ``` {% code title="Example Command Output" %} ``` Error: Service connector 'gcp-empty-sa' verification failed: connector authorization failure: failed to fetch GCS bucket zenml-bucket-sl: 403 GET https://storage.googleapis.com/storage/v1/b/zenml-bucket-sl?projection=noAcl&prettyPrint=false: empty-connectors@zenml-core.iam.gserviceaccount.com does not have storage.buckets.get access to the Google Cloud Storage bucket. Permission 'storage.buckets.get' denied on resource (or it may not exist). ``` {% endcode %} Next, we'll register a GCP Service Connector that actually uses account impersonation to access the `zenml-bucket-sl` GCS bucket and verify that it can actually access the bucket: ```sh zenml service-connector register gcp-impersonate-sa --type gcp --auth-method impersonation --service_account_json=@empty-connectors@zenml-core.json --project_id=zenml-core --target_principal=zenml-bucket-sl@zenml-core.iam.gserviceaccount.com --resource-type gcs-bucket --resource-id gs://zenml-bucket-sl ``` {% code title="Example Command Output" %} ``` Expanding argument value service_account_json to contents of file /home/stefan/aspyre/src/zenml/empty-connectors@zenml-core.json. Successfully registered service connector `gcp-impersonate-sa` with access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼──────────────────────┨ ┃ 📦 gcs-bucket │ gs://zenml-bucket-sl ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
### External Account (GCP Workload Identity) Use [GCP workload identity federation](https://cloud.google.com/iam/docs/workload-identity-federation) to authenticate to GCP services using AWS IAM credentials, Azure Active Directory credentials or generic OIDC tokens. This authentication method only requires a GCP workload identity external account JSON file that only contains the configuration for the external account without any sensitive credentials. It allows implementing [a two layer authentication scheme](best-security-practices.md#impersonating-accounts-and-assuming-roles) that keeps the set of permissions associated with implicit credentials down to the bare minimum and grants permissions to the privilege-bearing GCP service account instead. This authentication method can be used to authenticate to GCP services using credentials from other cloud providers or identity providers. When used with workloads running on AWS or Azure, it involves automatically picking up credentials from the AWS IAM or Azure AD identity associated with the workload and using them to authenticate to GCP services. This means that the result depends on the environment where the ZenML server is deployed and is thus not fully reproducible. {% hint style="warning" %} When used with AWS or Azure implicit in-cloud authentication, this method may constitute a security risk, because it can give users access to the identity (e.g. AWS IAM role or Azure AD principal) implicitly associated with the environment where the ZenML server is running. For this reason, all implicit authentication methods are disabled by default and need to be explicitly enabled by setting the `ZENML_ENABLE_IMPLICIT_AUTH_METHODS` environment variable or the helm chart `enableImplicitAuthMethods` configuration option to `true` in the ZenML deployment. {% endhint %} By default, the GCP connector generates temporary OAuth 2.0 tokens from the external account credentials and distributes them to clients. The tokens have a limited lifetime of 1 hour. This behavior can be disabled by setting the `generate_temporary_tokens` configuration option to `False`, in which case, the connector will distribute the external account credentials JSON to clients instead (not recommended). A GCP project is required and the connector may only be used to access GCP resources in the specified roject. This project must be the same as the one for which the external account was configured. If you already have the GOOGLE\_APPLICATION\_CREDENTIALS environment variable configured to point to an external account key JSON file, it will be automatically picked up when auto-configuration is used.
Example configuration The following assumes the following prerequisites are met, as covered in [the GCP documentation on how to configure workload identity federation with AWS](https://cloud.google.com/iam/docs/workload-identity-federation-with-other-clouds): * the ZenML server is deployed in AWS in an EKS cluster (or any other AWS compute environment) * the ZenML server EKS pods are associated with an AWS IAM role by means of an IAM OIDC provider, as covered in the [AWS documentation on how to associate a IAM role with a service account](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html). Alternatively, [the IAM role associated with the EKS/EC2 nodes](https://docs.aws.amazon.com/eks/latest/userguide/create-node-role.html) can be used instead. This AWS IAM role provides the implicit AWS IAM identity and credentials that will be used to authenticate to GCP services. * a GCP workload identity pool and AWS provider are configured for the GCP project where the target resources are located, as covered in [the GCP documentation on how to configure workload identity federation with AWS](https://cloud.google.com/iam/docs/workload-identity-federation-with-other-clouds). * a GCP service account is configured with permissions to access the target resources and granted the `roles/iam.workloadIdentityUser` role for the workload identity pool and AWS provider * a GCP external account JSON file is generated for the GCP service account. This is used to configure the GCP connector. ```sh zenml service-connector register gcp-workload-identity --type gcp \ --auth-method external-account --project_id=zenml-core \ --external_account_json=@clientLibraryConfig-aws-zenml.json ``` {% code title="Example Command Output" %} ``` Successfully registered service connector `gcp-workload-identity` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 📦 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 ┃ ┃ │ gs://zenml-project-time-series-bucket ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🐳 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 %} No sensitive credentials are stored with the Service Connector, just meta-information about the external provider and the external account: ```sh zenml service-connector describe gcp-workload-identity -x ``` {% code title="Example Command Output" %} ``` Service connector 'gcp-workload-identity' of type 'gcp' with id '37b6000e-3f7f-483e-b2c5-7a5db44fe66b' is owned by user 'default'. 'gcp-workload-identity' gcp Service Connector Details ┏━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ ID │ 37b6000e-3f7f-483e-b2c5-7a5db44fe66b ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ gcp-workload-identity ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔵 gcp ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ external-account ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔵 gcp-generic, 📦 gcs-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ 1ff6557f-7f60-4e63-b73d-650e64f015b5 ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES_SKEW_TOLERANCE │ N/A ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2024-01-30 20:44:14.020514 ┃ ┠────────────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2024-01-30 20:44:14.020516 ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────────────────────────────────────────────────────────────────────────┨ ┃ project_id │ zenml-core ┃ ┠───────────────────────┼───────────────────────────────────────────────────────────────────────────────┨ ┃ external_account_json │ { ┃ ┃ │ "type": "external_account", ┃ ┃ │ "audience": ┃ ┃ │ "//iam.googleapis.com/projects/30267569827/locations/global/workloadIdentityP ┃ ┃ │ ools/mypool/providers/myprovider", ┃ ┃ │ "subject_token_type": "urn:ietf:params:aws:token-type:aws4_request", ┃ ┃ │ "service_account_impersonation_url": ┃ ┃ │ "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/myrole@ ┃ ┃ │ zenml-core.iam.gserviceaccount.com:generateAccessToken", ┃ ┃ │ "token_url": "https://sts.googleapis.com/v1/token", ┃ ┃ │ "credential_source": { ┃ ┃ │ "environment_id": "aws1", ┃ ┃ │ "region_url": ┃ ┃ │ "http://169.254.169.254/latest/meta-data/placement/availability-zone", ┃ ┃ │ "url": ┃ ┃ │ "http://169.254.169.254/latest/meta-data/iam/security-credentials", ┃ ┃ │ "regional_cred_verification_url": ┃ ┃ │ "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06- ┃ ┃ │ 15" ┃ ┃ │ } ┃ ┃ │ } ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
### GCP OAuth 2.0 token Uses [temporary OAuth 2.0 tokens](best-security-practices.md#short-lived-credentials) explicitly configured by the user. This method has the major limitation that the user must regularly generate new tokens and update the connector configuration as OAuth 2.0 tokens expire. On the other hand, this method is ideal in cases where the connector only needs to be used for a short period of time, such as sharing access temporarily with someone else in your team. Using any of the other authentication methods will automatically generate and refresh OAuth 2.0 tokens for clients upon request. A GCP project is required and the connector may only be used to access GCP resources in the specified project.
Example auto-configuration Fetching OAuth 2.0 tokens from the local GCP CLI is possible if the GCP CLI is already configured with valid credentials (i.e. by running `gcloud auth application-default login`). We need to force the ZenML CLI to use the OAuth 2.0 token authentication by passing the `--auth-method oauth2-token` option, otherwise, it would automatically pick up long-term credentials: ```sh zenml service-connector register gcp-oauth2-token --type gcp --auto-configure --auth-method oauth2-token ``` {% code title="Example Command Output" %} ``` Successfully registered service connector `gcp-oauth2-token` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 📦 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 ┃ ┃ │ gs://zenml-project-time-series-bucket ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🐳 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 %} ```sh zenml service-connector describe gcp-oauth2-token ``` {% code title="Example Command Output" %} ``` Service connector 'gcp-oauth2-token' of type 'gcp' with id 'ec4d7d85-c71c-476b-aa76-95bf772c90da' is owned by user 'default' and is 'private'. 'gcp-oauth2-token' gcp Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ ID │ ec4d7d85-c71c-476b-aa76-95bf772c90da ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ gcp-oauth2-token ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔵 gcp ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ oauth2-token ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔵 gcp-generic, 📦 gcs-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ 4694de65-997b-4929-8831-b49d5e067b97 ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ 59m46s ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-05-19 09:04:33.557126 ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-05-19 09:04:33.557127 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━┯━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠────────────┼────────────┨ ┃ project_id │ zenml-core ┃ ┠────────────┼────────────┨ ┃ token │ [HIDDEN] ┃ ┗━━━━━━━━━━━━┷━━━━━━━━━━━━┛ ``` {% endcode %} Note the temporary nature of the Service Connector. It will expire and become unusable in 1 hour: ```sh zenml service-connector list --name gcp-oauth2-token ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼──────────────────┼──────────────────────────────────────┼────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ gcp-oauth2-token │ ec4d7d85-c71c-476b-aa76-95bf772c90da │ 🔵 gcp │ 🔵 gcp-generic │ │ ➖ │ default │ 59m35s │ ┃ ┃ │ │ │ │ 📦 gcs-bucket │ │ │ │ │ ┃ ┃ │ │ │ │ 🌀 kubernetes-cluster │ │ │ │ │ ┃ ┃ │ │ │ │ 🐳 docker-registry │ │ │ │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┛ ``` {% endcode %}
## Auto-configuration The GCP Service Connector allows [auto-discovering and fetching credentials](service-connectors-guide.md#auto-configuration) and configuration [set up by the GCP CLI](https://cloud.google.com/sdk/gcloud) on your local host.
Auto-configuration example The following is an example of lifting GCP user credentials granting access to the same set of GCP resources and services that the local GCP CLI is allowed to access. The GCP CLI should already be configured with valid credentials (i.e. by running `gcloud auth application-default login`). In this case, the [GCP user account authentication method](gcp-service-connector.md#gcp-user-account) is automatically detected: ```sh zenml service-connector register gcp-auto --type gcp --auto-configure ``` {% code title="Example Command Output" %} ``` Successfully registered service connector `gcp-auto` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 📦 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 ┃ ┃ │ gs://zenml-project-time-series-bucket ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🐳 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 %} ```sh zenml service-connector describe gcp-auto ``` {% code title="Example Command Output" %} ``` Service connector 'gcp-auto' of type 'gcp' with id 'fe16f141-7406-437e-a579-acebe618a293' is owned by user 'default' and is 'private'. 'gcp-auto' gcp Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ ID │ fe16f141-7406-437e-a579-acebe618a293 ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ NAME │ gcp-auto ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ TYPE │ 🔵 gcp ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ AUTH METHOD │ user-account ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🔵 gcp-generic, 📦 gcs-bucket, 🌀 kubernetes-cluster, 🐳 docker-registry ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SECRET ID │ 5eca8f6e-291f-4958-ae2d-a3e847a1ad8a ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-05-19 09:15:12.882929 ┃ ┠──────────────────┼──────────────────────────────────────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-05-19 09:15:12.882930 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────┼────────────┨ ┃ project_id │ zenml-core ┃ ┠───────────────────┼────────────┨ ┃ user_account_json │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┛ ``` {% endcode %}
## Local client provisioning The local `gcloud` CLI, the Kubernetes `kubectl` CLI and the Docker CLI can be[ configured with credentials extracted from or generated by a compatible GCP Service Connector](service-connectors-guide.md#configure-local-clients). Please note that unlike the configuration made possible through the GCP CLI, the Kubernetes and Docker credentials issued by the GCP Service Connector have a short lifetime and will need to be regularly refreshed. This is a byproduct of implementing a high-security profile. {% hint style="info" %} Note that the `gcloud` local client can only be configured with credentials issued by the GCP Service Connector if the connector is configured with the [GCP user account authentication method](gcp-service-connector.md#gcp-user-account) or the [GCP service account authentication method](gcp-service-connector.md#gcp-service-account) and if the `generate_temporary_tokens` option is set to true in the Service Connector configuration. Only the `gcloud` local [application default credentials](https://cloud.google.com/docs/authentication/application-default-credentials) configuration will be updated by the GCP Service Connector configuration. This makes it possible to use libraries and SDKs that use the application default credentials to access GCP resources. {% endhint %}
Local CLI configuration examples The following shows an example of configuring the local Kubernetes CLI to access a GKE cluster reachable through a GCP Service Connector: ```sh zenml service-connector list --name gcp-user-account ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼──────────────────┼──────────────────────────────────────┼────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ gcp-user-account │ ddbce93f-df14-4861-a8a4-99a80972f3bc │ 🔵 gcp │ 🔵 gcp-generic │ │ ➖ │ default │ │ ┃ ┃ │ │ │ │ 📦 gcs-bucket │ │ │ │ │ ┃ ┃ │ │ │ │ 🌀 kubernetes-cluster │ │ │ │ │ ┃ ┃ │ │ │ │ 🐳 docker-registry │ │ │ │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┛ ``` {% endcode %} The following lists all Kubernetes clusters accessible through the GCP Service Connector: ```sh zenml service-connector verify gcp-user-account --resource-type kubernetes-cluster ``` {% code title="Example Command Output" %} ``` Service connector 'gcp-user-account' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} Calling the login CLI command will configure the local Kubernetes `kubectl` CLI to access the Kubernetes cluster through the GCP Service Connector: ```sh zenml service-connector login gcp-user-account --resource-type kubernetes-cluster --resource-id zenml-test-cluster ``` {% code title="Example Command Output" %} ``` ⠴ Attempting to configure local client using service connector 'gcp-user-account'... Context "gke_zenml-core_zenml-test-cluster" modified. Updated local kubeconfig with the cluster details. The current kubectl context was set to 'gke_zenml-core_zenml-test-cluster'. The 'gcp-user-account' Kubernetes Service Connector connector was used to successfully configure the local Kubernetes cluster client/SDK. ``` {% endcode %} To verify that the local Kubernetes `kubectl` CLI is correctly configured, the following command can be used: ```sh kubectl cluster-info ``` {% code title="Example Command Output" %} ``` Kubernetes control plane is running at https://35.185.95.223 GLBCDefaultBackend is running at https://35.185.95.223/api/v1/namespaces/kube-system/services/default-http-backend:http/proxy KubeDNS is running at https://35.185.95.223/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy Metrics-server is running at https://35.185.95.223/api/v1/namespaces/kube-system/services/https:metrics-server:/proxy ``` {% endcode %} A similar process is possible with GCR container registries: ```sh zenml service-connector verify gcp-user-account --resource-type docker-registry --resource-id europe-west1-docker.pkg.dev/zenml-core/test ``` {% code title="Example Command Output" %} ``` Service connector 'gcp-user-account' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠────────────────────┼─────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ europe-west1-docker.pkg.dev/zenml-core/test ┃ ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector login gcp-user-account --resource-type docker-registry --resource-id europe-west1-docker.pkg.dev/zenml-core/test ``` {% code title="Example Command Output" %} ``` ⠦ Attempting to configure local client using service connector 'gcp-user-account'... 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-user-account' Docker Service Connector connector was used to successfully configure the local Docker/OCI container registry client/SDK. ``` {% endcode %} To verify that the local Docker container registry client is correctly configured, the following command can be used: ```sh docker push europe-west1-docker.pkg.dev/zenml-core/test/zenml ``` {% code title="Example Command Output" %} ``` The push refers to repository [europe-west1-docker.pkg.dev/zenml-core/test/zenml] d4aef4f5ed86: Pushed 2d69a4ce1784: Pushed 204066eca765: Pushed 2da74ab7b0c1: Pushed 75c35abda1d1: Layer already exists 415ff8f0f676: Layer already exists c14cb5b1ec91: Layer already exists a1d005f5264e: Layer already exists 3a3fd880aca3: Layer already exists 149a9c50e18e: Layer already exists 1f6d3424b922: Layer already exists 8402c959ae6f: Layer already exists 419599cb5288: Layer already exists 8553b91047da: Layer already exists connectors: digest: sha256:a4cfb18a5cef5b2201759a42dd9fe8eb2f833b788e9d8a6ebde194765b42fe46 size: 3256 ``` {% endcode %} It is also possible to update the local `gcloud` CLI configuration with credentials extracted from the GCP Service Connector: ```sh zenml service-connector login gcp-user-account --resource-type gcp-generic ``` {% code title="Example Command Output" %} ``` Updated the local gcloud default application credentials file at '/home/user/.config/gcloud/application_default_credentials.json' The 'gcp-user-account' GCP Service Connector connector was used to successfully configure the local Generic GCP resource client/SDK. ``` {% endcode %}
## Stack Components use The[ GCS Artifact Store Stack Component](../../../component-guide/artifact-stores/gcp.md) can be connected to a remote GCS bucket through a GCP Service Connector. The [Google Cloud Image Builder Stack Component](../../../component-guide/image-builders/gcp.md), [VertexAI Orchestrator](../../../component-guide/orchestrators/vertex.md), and [VertexAI Step Operator](../../../component-guide/step-operators/vertex.md) can be connected and use the resources of a target GCP project through a GCP Service Connector. The GCP Service Connector can also be used with any Orchestrator or Model Deployer stack component flavor that relies on Kubernetes clusters to manage workloads. This allows GKE Kubernetes container workloads to be managed without the need to configure and maintain explicit GCP or Kubernetes `kubectl` configuration contexts and credentials in the target environment or in the Stack Component itself. Similarly, Container Registry Stack Components can be connected to a Google Artifact Registry or GCR Container Registry through a GCP Service Connector. This allows container images to be built and published to GAR or GCR container registries without the need to configure explicit GCP credentials in the target environment or the Stack Component. ## End-to-end examples
GKE Kubernetes Orchestrator, GCS Artifact Store and GCR Container Registry with a multi-type GCP Service Connector This is an example of an end-to-end workflow involving Service Connectors that use a single multi-type GCP Service Connector to give access to multiple resources for multiple Stack Components. A complete ZenML Stack is registered and composed of the following Stack Components, all connected through the same Service Connector: * a [Kubernetes Orchestrator](../../../component-guide/orchestrators/kubernetes.md) connected to a GKE Kubernetes cluster * a [GCS Artifact Store](../../../component-guide/artifact-stores/gcp.md) connected to a GCS bucket * a [GCP Container Registry](../../../component-guide/container-registries/gcp.md) connected to a Docker Google Artifact Registry * a local [Image Builder](../../../component-guide/image-builders/local.md) As a last step, a simple pipeline is run on the resulting Stack. 1. Configure the local GCP CLI with valid user account credentials with a wide range of permissions (i.e. by running `gcloud auth application-default login`) and install ZenML integration prerequisites: ```sh zenml integration install -y gcp ``` ```sh gcloud auth application-default login ``` {% code title="Example Command Output" %} ```` ```text Credentials saved to file: [/home/stefan/.config/gcloud/application_default_credentials.json] These credentials will be used by any library that requests Application Default Credentials (ADC). Quota project "zenml-core" was added to ADC which can be used by Google client libraries for billing and quota. Note that some services may still bill the project owning the resource. ``` ```` {% endcode %} 2. Make sure the GCP Service Connector Type is available ```sh zenml service-connector list-types --type gcp ``` {% code title="Example Command Output" %} ```` ```text ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ 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 │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` ```` {% endcode %} 3. Register a multi-type GCP Service Connector using auto-configuration ```sh zenml service-connector register gcp-demo-multi --type gcp --auto-configure ``` {% code title="Example Command Output" %} ```` ```text Successfully registered service connector `gcp-demo-multi` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 📦 gcs-bucket │ gs://zenml-bucket-sl ┃ ┃ │ gs://zenml-core.appspot.com ┃ ┃ │ gs://zenml-core_cloudbuild ┃ ┃ │ gs://zenml-datasets ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🐳 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**: from this point forward, we don't need the local GCP CLI credentials or the local GCP CLI at all. The steps that follow can be run on any machine regardless of whether it has been configured and authorized to access the GCP project. ``` 4\. find out which GCS buckets, GAR registries, and GKE Kubernetes clusters we can gain access to. We'll use this information to configure the Stack Components in our minimal GCP stack: a GCS Artifact Store, a Kubernetes Orchestrator, and a GCP Container Registry. ```` ```sh zenml service-connector list-resources --resource-type gcs-bucket ``` ```` {% code title="Example Command Output" %} ```` ```text The following 'gcs-bucket' resources can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────┼─────────────────────────────────────────────────┨ ┃ eeeabc13-9203-463b-aa52-216e629e903c │ gcp-demo-multi │ 🔵 gcp │ 📦 gcs-bucket │ gs://zenml-bucket-sl ┃ ┃ │ │ │ │ gs://zenml-core.appspot.com ┃ ┃ │ │ │ │ gs://zenml-core_cloudbuild ┃ ┃ │ │ │ │ gs://zenml-datasets ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} ```` ```sh zenml service-connector list-resources --resource-type kubernetes-cluster ``` ```` {% code title="Example Command Output" %} ```` ```text 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 ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────────────┼────────────────────┨ ┃ eeeabc13-9203-463b-aa52-216e629e903c │ gcp-demo-multi │ 🔵 gcp │ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} ```` ```sh zenml service-connector list-resources --resource-type docker-registry ``` ```` {% code title="Example Command Output" %} ```` ```text 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 ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────────┼─────────────────────────────────────────────────┨ ┃ eeeabc13-9203-463b-aa52-216e629e903c │ gcp-demo-multi │ 🔵 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 %} 5. register and connect a GCS Artifact Store Stack Component to a GCS bucket: ```sh zenml artifact-store register gcs-zenml-bucket-sl --flavor gcp --path=gs://zenml-bucket-sl ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (global) Successfully registered artifact_store `gcs-zenml-bucket-sl`. ``` ```` {% endcode %} ```` ```sh zenml artifact-store connect gcs-zenml-bucket-sl --connector gcp-demo-multi ``` ```` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (global) Successfully connected artifact store `gcs-zenml-bucket-sl` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────┼──────────────────────┨ ┃ eeeabc13-9203-463b-aa52-216e629e903c │ gcp-demo-multi │ 🔵 gcp │ 📦 gcs-bucket │ gs://zenml-bucket-sl ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 6. register and connect a Kubernetes Orchestrator Stack Component to a GKE cluster: ```sh zenml orchestrator register gke-zenml-test-cluster --flavor kubernetes --synchronous=true --kubernetes_namespace=zenml-workloads ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (global) Successfully registered orchestrator `gke-zenml-test-cluster`. ``` ```` {% endcode %} ```` ```sh zenml orchestrator connect gke-zenml-test-cluster --connector gcp-demo-multi ``` ```` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (global) Successfully connected orchestrator `gke-zenml-test-cluster` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────────────┼────────────────────┨ ┃ eeeabc13-9203-463b-aa52-216e629e903c │ gcp-demo-multi │ 🔵 gcp │ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 7. Register and connect a GCP Container Registry Stack Component to a GAR registry: ```sh zenml container-registry register gcr-zenml-core --flavor gcp --uri=europe-west1-docker.pkg.dev/zenml-core/test ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (global) Successfully registered container_registry `gcr-zenml-core`. ``` ```` {% endcode %} ```` ```sh zenml container-registry connect gcr-zenml-core --connector gcp-demo-multi ``` ```` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (global) Successfully connected container registry `gcr-zenml-core` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────────┼─────────────────────────────────────────────┨ ┃ eeeabc13-9203-463b-aa52-216e629e903c │ gcp-demo-multi │ 🔵 gcp │ 🐳 docker-registry │ europe-west1-docker.pkg.dev/zenml-core/test ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 8. Combine all Stack Components together into a Stack and set it as active (also throw in a local Image Builder for completion): ```sh zenml image-builder register local --flavor local ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (global) Successfully registered image_builder `local`. ``` ```` {% endcode %} ```` ```sh zenml stack register gcp-demo -a gcs-zenml-bucket-sl -o gke-zenml-test-cluster -c gcr-zenml-core -i local --set ``` ```` {% code title="Example Command Output" %} ```` ```text Stack 'gcp-demo' successfully registered! Active global stack set to:'gcp-demo' ``` ```` {% endcode %} 9. Finally, run a simple pipeline to prove that everything works as expected. We'll use the simplest pipelines possible for this example: ```python from zenml import pipeline, step @step def step_1() -> str: """Returns the `world` string.""" return "world" @step(enable_cache=False) def step_2(input_one: str, input_two: str) -> None: """Combines the two strings at its input and prints them.""" combined_str = f"{input_one} {input_two}" print(combined_str) @pipeline def my_pipeline(): output_step_one = step_1() step_2(input_one="hello", input_two=output_step_one) if __name__ == "__main__": my_pipeline() ``` Saving that to a `run.py` file and running it gives us: {% code title="Example Command Output" %} ```` ```text $ python run.py Building Docker image(s) for pipeline simple_pipeline. Building Docker image europe-west1-docker.pkg.dev/zenml-core/test/zenml:simple_pipeline-orchestrator. - Including integration requirements: gcsfs, google-cloud-aiplatform>=1.11.0, google-cloud-build>=3.11.0, google-cloud-container>=2.21.0, google-cloud-functions>=1.8.3, google-cloud-scheduler>=2.7.3, google-cloud-secret-manager, google-cloud-storage>=2.9.0, kfp==1.8.16, kubernetes==18.20.0, shapely<2.0 No .dockerignore found, including all files inside build context. Step 1/8 : FROM zenmldocker/zenml:0.39.1-py3.8 Step 2/8 : WORKDIR /app Step 3/8 : COPY .zenml_integration_requirements . Step 4/8 : RUN pip install --default-timeout=60 --no-cache-dir -r .zenml_integration_requirements Step 5/8 : ENV ZENML_ENABLE_REPO_INIT_WARNINGS=False Step 6/8 : ENV ZENML_CONFIG_PATH=/app/.zenconfig Step 7/8 : COPY . . Step 8/8 : RUN chmod -R a+rw . Pushing Docker image europe-west1-docker.pkg.dev/zenml-core/test/zenml:simple_pipeline-orchestrator. Finished pushing Docker image. Finished building Docker image(s). Running pipeline simple_pipeline on stack gcp-demo (caching disabled) Waiting for Kubernetes orchestrator pod... Kubernetes orchestrator pod started. Waiting for pod of step step_1 to start... Step step_1 has started. Step step_1 has finished in 1.357s. Pod of step step_1 completed. Waiting for pod of step simple_step_two to start... Step step_2 has started. Hello World! Step step_2 has finished in 3.136s. Pod of step step_2 completed. Orchestration pod completed. Dashboard URL: http://34.148.132.191/default/pipelines/cec118d1-d90a-44ec-8bd7-d978f726b7aa/runs ``` ```` {% endcode %}
VertexAI Orchestrator, GCS Artifact Store, Google Artifact Registry and GCP Image Builder with single-instance GCP Service Connectors This is an example of an end-to-end workflow involving Service Connectors that use multiple single-instance GCP Service Connectors, each giving access to a resource for a Stack Component. A complete ZenML Stack is registered and composed of the following Stack Components, all connected through its individual Service Connector: * a [VertexAI Orchestrator](../../../component-guide/orchestrators/vertex.md) connected to the GCP project * a [GCS Artifact Store](../../../component-guide/artifact-stores/gcp.md) connected to a GCS bucket * a [GCP Container Registry](../../../component-guide/container-registries/gcp.md) connected to a GCR container registry * a [Google Cloud Image Builder](../../../component-guide/image-builders/gcp.md) connected to the GCP project As a last step, a simple pipeline is run on the resulting Stack. 1. Configure the local GCP CLI with valid user account credentials with a wide range of permissions (i.e. by running `gcloud auth application-default login`) and install ZenML integration prerequisites: ```sh zenml integration install -y gcp ``` ```sh gcloud auth application-default login ``` {% code title="Example Command Output" %} ```` ```text Credentials saved to file: [/home/stefan/.config/gcloud/application_default_credentials.json] These credentials will be used by any library that requests Application Default Credentials (ADC). Quota project "zenml-core" was added to ADC which can be used by Google client libraries for billing and quota. Note that some services may still bill the project owning the resource. ``` ```` {% endcode %} 2. Make sure the GCP Service Connector Type is available ```sh zenml service-connector list-types --type gcp ``` {% code title="Example Command Output" %} ```` ```text ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ 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 │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` ```` {% endcode %} 3. Register an individual single-instance GCP Service Connector using auto-configuration for each of the resources that will be needed for the Stack Components: a GCS bucket, a GCR registry, and generic GCP access for the VertexAI orchestrator and another one for the GCP Cloud Builder: ```sh zenml service-connector register gcs-zenml-bucket-sl --type gcp --resource-type gcs-bucket --resource-id gs://zenml-bucket-sl --auto-configure ``` {% code title="Example Command Output" %} ```` ```text 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 %} ```` ```sh zenml service-connector register gcr-zenml-core --type gcp --resource-type docker-registry --auto-configure ``` ```` {% code title="Example Command Output" %} ```` ```text Successfully registered service connector `gcr-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 %} ```` ```sh zenml service-connector register vertex-ai-zenml-core --type gcp --resource-type gcp-generic --auto-configure ``` ```` {% code title="Example Command Output" %} ```` ```text Successfully registered service connector `vertex-ai-zenml-core` with access to the following resources: ┏━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠────────────────┼────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┗━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} ```` ```sh zenml service-connector register gcp-cloud-builder-zenml-core --type gcp --resource-type gcp-generic --auto-configure ``` ```` {% code title="Example Command Output" %} ```` ```text Successfully registered service connector `gcp-cloud-builder-zenml-core` with access to the following resources: ┏━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠────────────────┼────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┗━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} ```` **NOTE**: from this point forward, we don't need the local GCP CLI credentials or the local GCP CLI at all. The steps that follow can be run on any machine regardless of whether it has been configured and authorized to access the GCP project. In the end, the service connector list should look like this: ```sh zenml service-connector list ``` ```` {% code title="Example Command Output" %} ```` ```text ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼──────────────────────────────┼──────────────────────────────────────┼────────┼────────────────────┼──────────────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ gcs-zenml-bucket-sl │ 405034fe-5e6e-4d29-ba62-8ae025381d98 │ 🔵 gcp │ 📦 gcs-bucket │ gs://zenml-bucket-sl │ ➖ │ default │ │ ┃ ┠────────┼──────────────────────────────┼──────────────────────────────────────┼────────┼────────────────────┼──────────────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ gcr-zenml-core │ 9fddfaba-6d46-4806-ad96-9dcabef74639 │ 🔵 gcp │ 🐳 docker-registry │ gcr.io/zenml-core │ ➖ │ default │ │ ┃ ┠────────┼──────────────────────────────┼──────────────────────────────────────┼────────┼────────────────────┼──────────────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ vertex-ai-zenml-core │ f97671b9-8c73-412b-bf5e-4b7c48596f5f │ 🔵 gcp │ 🔵 gcp-generic │ zenml-core │ ➖ │ default │ │ ┃ ┠────────┼──────────────────────────────┼──────────────────────────────────────┼────────┼────────────────────┼──────────────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ gcp-cloud-builder-zenml-core │ 648c1016-76e4-4498-8de7-808fd20f057b │ 🔵 gcp │ 🔵 gcp-generic │ zenml-core │ ➖ │ default │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┛ ``` ```` {% endcode %} 4. register and connect a GCS Artifact Store Stack Component to the GCS bucket: ```sh zenml artifact-store register gcs-zenml-bucket-sl --flavor gcp --path=gs://zenml-bucket-sl ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (global) Successfully registered artifact_store `gcs-zenml-bucket-sl`. ``` ```` {% endcode %} ```` ```sh zenml artifact-store connect gcs-zenml-bucket-sl --connector gcs-zenml-bucket-sl ``` ```` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (global) Successfully connected artifact store `gcs-zenml-bucket-sl` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼─────────────────────┼────────────────┼───────────────┼──────────────────────┨ ┃ 405034fe-5e6e-4d29-ba62-8ae025381d98 │ gcs-zenml-bucket-sl │ 🔵 gcp │ 📦 gcs-bucket │ gs://zenml-bucket-sl ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 5. register and connect a Google Cloud Image Builder Stack Component to the target GCP project: ```sh zenml image-builder register gcp-zenml-core --flavor gcp ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully registered image_builder `gcp-zenml-core`. ``` ```` {% endcode %} ```` ```sh zenml image-builder connect gcp-zenml-core --connector gcp-cloud-builder-zenml-core ``` ```` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully connected image builder `gcp-zenml-core` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼──────────────────────────────┼────────────────┼────────────────┼────────────────┨ ┃ 648c1016-76e4-4498-8de7-808fd20f057b │ gcp-cloud-builder-zenml-core │ 🔵 gcp │ 🔵 gcp-generic │ zenml-core ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 6. register and connect a Vertex AI Orchestrator Stack Component to the target GCP project **NOTE**: If we do not specify a workload service account, the Vertex AI Pipelines Orchestrator uses the Compute Engine default service account in the target project to run pipelines. You must grant this account the Vertex AI Service Agent role, otherwise the pipelines will fail. More information on other configurations possible for the Vertex AI Orchestrator can be found [here](../../../component-guide/orchestrators/vertex.md#how-to-use-it). ```sh zenml orchestrator register vertex-ai-zenml-core --flavor=vertex --location=europe-west1 --synchronous=true ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully registered orchestrator `vertex-ai-zenml-core`. ``` ```` {% endcode %} ```` ```sh zenml orchestrator connect vertex-ai-zenml-core --connector vertex-ai-zenml-core ``` ```` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully connected orchestrator `vertex-ai-zenml-core` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼──────────────────────┼────────────────┼────────────────┼────────────────┨ ┃ f97671b9-8c73-412b-bf5e-4b7c48596f5f │ vertex-ai-zenml-core │ 🔵 gcp │ 🔵 gcp-generic │ zenml-core ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 7. Register and connect a GCP Container Registry Stack Component to a GCR container registry: ```sh zenml container-registry register gcr-zenml-core --flavor gcp --uri=gcr.io/zenml-core ``` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully registered container_registry `gcr-zenml-core`. ``` ```` {% endcode %} ```` ```sh zenml container-registry connect gcr-zenml-core --connector gcr-zenml-core ``` ```` {% code title="Example Command Output" %} ```` ```text Running with active stack: 'default' (repository) Successfully connected container registry `gcr-zenml-core` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼────────────────────┼───────────────────┨ ┃ 9fddfaba-6d46-4806-ad96-9dcabef74639 │ gcr-zenml-core │ 🔵 gcp │ 🐳 docker-registry │ gcr.io/zenml-core ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┛ ``` ```` {% endcode %} 8. Combine all Stack Components together into a Stack and set it as active: ```sh zenml stack register gcp-demo -a gcs-zenml-bucket-sl -o vertex-ai-zenml-core -c gcr-zenml-core -i gcp-zenml-core --set ``` {% code title="Example Command Output" %} ```` ```text Stack 'gcp-demo' successfully registered! Active repository stack set to:'gcp-demo' ``` ```` {% endcode %} 9. Finally, run a simple pipeline to prove that everything works as expected. We'll use the simplest pipelines possible for this example: ```python from zenml import pipeline, step @step def step_1() -> str: """Returns the `world` string.""" return "world" @step(enable_cache=False) def step_2(input_one: str, input_two: str) -> None: """Combines the two strings at its input and prints them.""" combined_str = f"{input_one} {input_two}" print(combined_str) @pipeline def my_pipeline(): output_step_one = step_1() step_2(input_one="hello", input_two=output_step_one) if __name__ == "__main__": my_pipeline() ``` Saving that to a `run.py` file and running it gives us: {% code title="Example Command Output" %} ```` ```text $ python run.py Building Docker image(s) for pipeline simple_pipeline. Building Docker image gcr.io/zenml-core/zenml:simple_pipeline-orchestrator. - Including integration requirements: gcsfs, google-cloud-aiplatform>=1.11.0, google-cloud-build>=3.11.0, google-cloud-container>=2.21.0, google-cloud-functions>=1.8.3, google-cloud-scheduler>=2.7.3, google-cloud-secret-manager, google-cloud-storage>=2.9.0, kfp==1.8.16, shapely<2.0 Using Cloud Build to build image gcr.io/zenml-core/zenml:simple_pipeline-orchestrator No .dockerignore found, including all files inside build context. Uploading build context to gs://zenml-bucket-sl/cloud-build-contexts/5dda6dbb60e036398bee4974cfe3eb768a138b2e.tar.gz. Build context located in bucket zenml-bucket-sl and object path cloud-build-contexts/5dda6dbb60e036398bee4974cfe3eb768a138b2e.tar.gz Using Cloud Builder image gcr.io/cloud-builders/docker to run the steps in the build. Container will be attached to network using option --network=cloudbuild. Running Cloud Build to build the Docker image. Cloud Build logs: https://console.cloud.google.com/cloud-build/builds/068e77a1-4e6f-427a-bf94-49c52270af7a?project=20219041791 The Docker image has been built successfully. More information can be found in the Cloud Build logs: https://console.cloud.google.com/cloud-build/builds/068e77a1-4e6f-427a-bf94-49c52270af7a?project=20219041791. Finished building Docker image(s). Running pipeline simple_pipeline on stack gcp-demo (caching disabled) The attribute pipeline_root has not been set in the orchestrator configuration. One has been generated automatically based on the path of the GCPArtifactStore artifact store in the stack used to execute the pipeline. The generated pipeline_root is gs://zenml-bucket-sl/vertex_pipeline_root/simple_pipeline/simple_pipeline_default_6e72f3e1. /home/stefan/aspyre/src/zenml/.venv/lib/python3.8/site-packages/kfp/v2/compiler/compiler.py:1290: FutureWarning: APIs imported from the v1 namespace (e.g. kfp.dsl, kfp.components, etc) will not be supported by the v2 compiler since v2.0.0 warnings.warn( Writing Vertex workflow definition to /home/stefan/.config/zenml/vertex/8a0b53ee-644a-4fbe-8e91-d4d6ddf79ae8/pipelines/simple_pipeline_default_6e72f3e1.json. No schedule detected. Creating one-off vertex job... Submitting pipeline job with job_id simple-pipeline-default-6e72f3e1 to Vertex AI Pipelines service. The Vertex AI Pipelines job workload will be executed using the connectors-vertex-ai-workload@zenml-core.iam.gserviceaccount.com service account. Creating PipelineJob INFO:google.cloud.aiplatform.pipeline_jobs:Creating PipelineJob PipelineJob created. Resource name: projects/20219041791/locations/europe-west1/pipelineJobs/simple-pipeline-default-6e72f3e1 INFO:google.cloud.aiplatform.pipeline_jobs:PipelineJob created. Resource name: projects/20219041791/locations/europe-west1/pipelineJobs/simple-pipeline-default-6e72f3e1 To use this PipelineJob in another session: INFO:google.cloud.aiplatform.pipeline_jobs:To use this PipelineJob in another session: pipeline_job = aiplatform.PipelineJob.get('projects/20219041791/locations/europe-west1/pipelineJobs/simple-pipeline-default-6e72f3e1') INFO:google.cloud.aiplatform.pipeline_jobs:pipeline_job = aiplatform.PipelineJob.get('projects/20219041791/locations/europe-west1/pipelineJobs/simple-pipeline-default-6e72f3e1') View Pipeline Job: https://console.cloud.google.com/vertex-ai/locations/europe-west1/pipelines/runs/simple-pipeline-default-6e72f3e1?project=20219041791 INFO:google.cloud.aiplatform.pipeline_jobs:View Pipeline Job: https://console.cloud.google.com/vertex-ai/locations/europe-west1/pipelines/runs/simple-pipeline-default-6e72f3e1?project=20219041791 View the Vertex AI Pipelines job at https://console.cloud.google.com/vertex-ai/locations/europe-west1/pipelines/runs/simple-pipeline-default-6e72f3e1?project=20219041791 Waiting for the Vertex AI Pipelines job to finish... PipelineJob projects/20219041791/locations/europe-west1/pipelineJobs/simple-pipeline-default-6e72f3e1 current state: PipelineState.PIPELINE_STATE_RUNNING INFO:google.cloud.aiplatform.pipeline_jobs:PipelineJob projects/20219041791/locations/europe-west1/pipelineJobs/simple-pipeline-default-6e72f3e1 current state: PipelineState.PIPELINE_STATE_RUNNING ... PipelineJob run completed. Resource name: projects/20219041791/locations/europe-west1/pipelineJobs/simple-pipeline-default-6e72f3e1 INFO:google.cloud.aiplatform.pipeline_jobs:PipelineJob run completed. Resource name: projects/20219041791/locations/europe-west1/pipelineJobs/simple-pipeline-default-6e72f3e1 Dashboard URL: https://34.148.132.191/default/pipelines/17cac6b5-3071-45fa-a2ef-cda4a7965039/runs ``` ```` {% endcode %}
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/auth-management/hyperai-service-connector.md ================ --- description: Configuring HyperAI Connectors to connect ZenML to HyperAI instances. --- # HyperAI Service Connector The ZenML HyperAI Service Connector allows authenticating with a HyperAI instance for deployment of pipeline runs. This connector provides pre-authenticated Paramiko SSH clients to Stack Components that are linked to it. ```shell $ zenml service-connector list-types --type hyperai ``` ```shell ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ NAME │ TYPE │ RESOURCE TYPES │ AUTH METHODS │ LOCAL │ REMOTE ┃ ┠───────────────────────────┼────────────┼────────────────────┼──────────────┼───────┼────────┨ ┃ HyperAI Service Connector │ 🤖 hyperai │ 🤖 hyperai-instance │ rsa-key │ ✅ │ ✅ ┃ ┃ │ │ │ dsa-key │ │ ┃ ┃ │ │ │ ecdsa-key │ │ ┃ ┃ │ │ │ ed25519-key │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` ## Prerequisites The HyperAI Service Connector is part of the HyperAI integration. It is necessary to install the integration in order to use this Service Connector: * `zenml integration install hyperai` installs the HyperAI integration ## Resource Types The HyperAI Service Connector supports HyperAI instances. ## Authentication Methods ZenML creates an SSH connection to the HyperAI instance in the background when using this Service Connector. It then provides these connections to stack components requiring them, such as the HyperAI Orchestrator. Multiple authentication methods are supported: 1. RSA key based authentication. 2. DSA (DSS) key based authentication. 3. ECDSA key based authentication. 4. ED25519 key based authentication. {% hint style="warning" %} SSH private keys configured in the connector will be distributed to all clients that use them to run pipelines with the HyperAI orchestrator. SSH keys are long-lived credentials that give unrestricted access to HyperAI instances. {% endhint %} When configuring the Service Connector, it is required to provide at least one hostname via `hostnames` and the `username` with which to login. Optionally, it is possible to provide an `ssh_passphrase` if applicable. This way, it is possible to use the HyperAI service connector in multiple ways: 1. Create one service connector per HyperAI instance with different SSH keys. 2. Configure a reused SSH key just once for multiple HyperAI instances, then select the individual instance when creating the HyperAI orchestrator component. ## Auto-configuration {% hint style="info" %} This Service Connector does not support auto-discovery and extraction of authentication credentials from HyperAI instances. If this feature is useful to you or your organization, please let us know by messaging us in [Slack](https://zenml.io/slack) or [creating an issue on GitHub](https://github.com/zenml-io/zenml/issues). {% endhint %} ## Stack Components use The HyperAI Service Connector can be used by the HyperAI Orchestrator to deploy pipeline runs to HyperAI instances.
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/auth-management/kubernetes-service-connector.md ================ --- description: Configuring Kubernetes Service Connectors to connect ZenML to Kubernetes clusters. --- # Kubernetes Service Connector The ZenML Kubernetes service connector facilitates authenticating and connecting to a Kubernetes cluster. The connector can be used to access to any generic Kubernetes cluster by providing pre-authenticated Kubernetes python clients to Stack Components that are linked to it and also allows configuring the local Kubernetes CLI (i.e. `kubectl`). ## Prerequisites The Kubernetes Service Connector is part of the Kubernetes ZenML integration. You can either install the entire integration or use a pypi extra to install it independently of the integration: * `pip install "zenml[connectors-kubernetes]"` installs only prerequisites for the Kubernetes Service Connector Type * `zenml integration install kubernetes` installs the entire Kubernetes ZenML integration A local Kubernetes CLI (i.e. `kubectl` ) and setting up local `kubectl` configuration contexts is not required to access Kubernetes clusters in your Stack Components through the Kubernetes Service Connector. ```shell $ zenml service-connector list-types --type kubernetes ``` ``` ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ NAME │ TYPE │ RESOURCE TYPES │ AUTH METHODS │ LOCAL │ REMOTE ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼──────────────┼───────┼────────┨ ┃ Kubernetes Service Connector │ 🌀 kubernetes │ 🌀 kubernetes-cluster │ password │ ✅ │ ✅ ┃ ┃ │ │ │ token │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` ## Resource Types The Kubernetes Service Connector only supports authenticating to and granting access to a generic Kubernetes cluster. This type of resource is identified by the `kubernetes-cluster` Resource Type. The resource name is a user-friendly cluster name configured during registration. ## Authentication Methods Two authentication methods are supported: 1. username and password. This is not recommended for production purposes. 2. authentication token with or without client certificates. For Kubernetes clusters that use neither username and password nor authentication tokens, such as local K3D clusters, the authentication token method can be used with an empty token. {% hint style="warning" %} This Service Connector does not support generating short-lived credentials from the credentials configured in the Service Connector. In effect, this means that the configured credentials will be distributed directly to clients and used to authenticate to the target Kubernetes API. It is recommended therefore to use API tokens accompanied by client certificates if possible. {% endhint %} ## Auto-configuration The Kubernetes Service Connector allows fetching credentials from the local Kubernetes CLI (i.e. `kubectl`) during registration. The current Kubernetes kubectl configuration context is used for this purpose. The following is an example of lifting Kubernetes credentials granting access to a GKE cluster: ```sh zenml service-connector register kube-auto --type kubernetes --auto-configure ``` {% code title="Example Command Output" %} ```text Successfully registered service connector `kube-auto` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼────────────────┨ ┃ 🌀 kubernetes-cluster │ 35.185.95.223 ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector describe kube-auto ``` {% code title="Example Command Output" %} ```text Service connector 'kube-auto' of type 'kubernetes' with id '4315e8eb-fcbd-4938-a4d7-a9218ab372a1' is owned by user 'default' and is 'private'. 'kube-auto' kubernetes Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ ID │ 4315e8eb-fcbd-4938-a4d7-a9218ab372a1 ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ NAME │ kube-auto ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ TYPE │ 🌀 kubernetes ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ AUTH METHOD │ token ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ RESOURCE TYPES │ 🌀 kubernetes-cluster ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ RESOURCE NAME │ 35.175.95.223 ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SECRET ID │ a833e86d-b845-4584-9656-4b041335e299 ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ CREATED_AT │ 2023-05-16 21:45:33.224740 ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-05-16 21:45:33.224743 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────────────────┨ ┃ server │ https://35.175.95.223 ┃ ┠───────────────────────┼───────────────────────┨ ┃ insecure │ False ┃ ┠───────────────────────┼───────────────────────┨ ┃ cluster_name │ 35.175.95.223 ┃ ┠───────────────────────┼───────────────────────┨ ┃ token │ [HIDDEN] ┃ ┠───────────────────────┼───────────────────────┨ ┃ certificate_authority │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} {% hint style="info" %} Credentials auto-discovered and lifted through the Kubernetes Service Connector might have a limited lifetime, especially if the target Kubernetes cluster is managed through a 3rd party authentication provider such a GCP or AWS. Using short-lived credentials with your Service Connectors could lead to loss of connectivity and other unexpected errors in your pipeline. {% endhint %} ## Local client provisioning This Service Connector allows configuring the local Kubernetes client (i.e. `kubectl`) with credentials: ```sh zenml service-connector login kube-auto ``` {% code title="Example Command Output" %} ```text ⠦ Attempting to configure local client using service connector 'kube-auto'... Cluster "35.185.95.223" set. ⠇ Attempting to configure local client using service connector 'kube-auto'... ⠏ Attempting to configure local client using service connector 'kube-auto'... Updated local kubeconfig with the cluster details. The current kubectl context was set to '35.185.95.223'. The 'kube-auto' Kubernetes Service Connector connector was used to successfully configure the local Kubernetes cluster client/SDK. ``` {% endcode %} ## Stack Components use The Kubernetes Service Connector can be used in Orchestrator and Model Deployer stack component flavors that rely on Kubernetes clusters to manage their workloads. This allows Kubernetes container workloads to be managed without the need to configure and maintain explicit Kubernetes `kubectl` configuration contexts and credentials in the target environment and in the Stack Component.
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/auth-management/README.md ================ --- icon: plug description: >- Connect your ZenML deployment to a cloud provider and other infrastructure services and resources. --- # Connect services (AWS, GCP, Azure, K8s etc) A production-grade MLOps platform involves interactions between a diverse combination of third-party libraries and external services sourced from various different vendors. One of the most daunting hurdles in building and operating an MLOps platform composed of multiple components is configuring and maintaining uninterrupted and secured access to the infrastructure resources and services that it consumes. In layman's terms, your pipeline code needs to "connect" to a handful of different services to run successfully and do what it's designed to do. For example, it might need to connect to a private AWS S3 bucket to read and store artifacts, a Kubernetes cluster to execute steps with Kubeflow or Tekton, and a private GCR container registry to build and store container images. ZenML makes this possible by allowing you to configure authentication information and credentials embedded directly into your Stack Components, but this doesn't scale well when you have more than a few Stack Components and has many other disadvantages related to usability and security. Gaining access to infrastructure resources and services requires knowledge about the different authentication and authorization mechanisms and involves configuring and maintaining valid credentials. It gets even more complicated when these different services need to access each other. For instance, the Kubernetes container running your pipeline step needs access to the S3 bucket to store artifacts or needs to access a cloud service like AWS SageMaker, VertexAI, or AzureML to run a CPU/GPU intensive task like training a model. The challenge comes from _setting up and implementing proper authentication and authorization_ with the best security practices in mind, while at the same time _keeping this complexity away from the day-to-day routines_ of coding and running pipelines. The hard-to-swallow truth is there is no single standard that unifies all authentication and authorization-related matters or a single, well-defined set of security best practices that you can follow. However, with ZenML you get the next best thing, an abstraction that keeps the complexity of authentication and authorization away from your code and makes it easier to tackle them: _the ZenML Service Connectors_.

Service Connectors abstract away complexity and implement security best practices

## A representative use-case The range of features covered by Service Connectors is extensive and going through the entire [Service Connector Guide](service-connectors-guide.md) can be overwhelming. If all you want is to get a quick overview of how Service Connectors work and what they can do for you, this section is for you. This is a representative example of how you would use a Service Connector to connect ZenML to a cloud service. This example uses [the AWS Service Connector](aws-service-connector.md) to connect ZenML to an AWS S3 bucket and then link [an S3 Artifact Store Stack Component](../../../component-guide/artifact-stores/s3.md) to it. Some details about the current alternatives to using Service Connectors and their drawbacks are provided below. Feel free to skip them if you are already familiar with them or just want to get to the good part.
Alternatives to Service Connectors There are quicker alternatives to using a Service Connector to link an S3 Artifact Store to a private AWS S3 bucket. Let's lay them out first and then explain why using a Service Connector is the better option: 1. the authentication information can be embedded directly into the Stack Component, although this is not recommended for security reasons: ```shell zenml artifact-store register s3 --flavor s3 --path=s3://BUCKET_NAME --key=AWS_ACCESS_KEY --secret=AWS_SECRET_KEY ``` 2. [a ZenML secret](../../../getting-started/deploying-zenml/secret-management.md) can hold the AWS credentials and then be referenced in the S3 Artifact Store configuration attributes: ```shell zenml secret create aws --aws_access_key_id=AWS_ACCESS_KEY --aws_secret_access_key=AWS_SECRET_KEY zenml artifact-store register s3 --flavor s3 --path=s3://BUCKET_NAME --key='{{aws.aws_access_key_id}}' --secret='{{aws.aws_secret_access_key}}' ``` 3. an even better version is to reference the secret itself in the S3 Artifact Store configuration: ```shell zenml secret create aws --aws_access_key_id=AWS_ACCESS_KEY --aws_secret_access_key=AWS_SECRET_KEY zenml artifact-store register s3 --flavor s3 --path=s3://BUCKET_NAME --authentication_secret=aws ``` All these options work, but they have many drawbacks: * first of all, not all Stack Components support referencing secrets in their configuration attributes, so this is not a universal solution. * some Stack Components, like those linked to Kubernetes clusters, rely on credentials being set up on the machine where the pipeline is running, which makes pipelines less portable and more difficult to set up. In other cases, you also need to install and set up cloud-specific SDKs and CLIs to be able to use the Stack Component. * people configuring and using Stack Components linked to cloud resources need to be given access to cloud credentials, or even provision the credentials themselves, which requires access to the cloud provider platform and knowledge about how to do it. * in many cases, you can only configure long-lived credentials directly in Stack Components. This is a security risk because they can inadvertently grant access to key resources and services to a malicious party if they are compromised. Implementing a process that rotates credentials regularly is a complex task that requires a lot of effort and maintenance. * Stack Components don't implement any kind of verification regarding the validity and permission of configured credentials. If the credentials are invalid or if they lack the proper permissions to access the remote resource or service, you will only find this out later, when running a pipeline will fail at runtime. * ultimately, given that different Stack Component flavors rely on the same type of resource or cloud provider, it is not good design to duplicate the logic that handles authentication and authorization in each Stack Component implementation. These drawbacks are addressed by Service Connectors.
Without Service Connectors, credentials are stored directly in the Stack Component configuration or ZenML Secret and are directly used in the runtime environment. The Stack Component implementation is directly responsible for validating credentials, authenticating and connecting to the infrastructure service. This is illustrated in the following diagram: ![Authentication without Service Connectors](../../../.gitbook/assets/authentication_without_connectors.png) When Service Connectors are involved in the authentication and authorization process, they can act as brokers. The credentials validation and authentication process takes place on the ZenML server. In most cases, the main credentials never have to leave the ZenML server as the Service Connector automatically converts them into short-lived credentials with a reduced set of privileges and issues these credentials to clients. Furthermore, multiple Stack Components of different flavors can use the same Service Connector to access different types or resources with the same credentials: ![Authentication with Service Connectors](../../../.gitbook/assets/authentication_with_connectors.png) In working with Service Connectors, the first step is usually _finding out what types of resources you can connect ZenML to_. Maybe you have already planned out the infrastructure options for your MLOps platform and are looking to find out whether ZenML can accommodate them. Or perhaps you want to use a particular Stack Component flavor in your Stack and are wondering whether you can use a Service Connector to connect it to external resources. Listing the available Service Connector Types will give you a good idea of what you can do with Service Connectors: ```sh zenml service-connector list-types ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ NAME │ TYPE │ RESOURCE TYPES │ AUTH METHODS │ LOCAL │ REMOTE ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼──────────────────┼───────┼────────┨ ┃ Kubernetes Service Connector │ 🌀 kubernetes │ 🌀 kubernetes-cluster │ password │ ✅ │ ✅ ┃ ┃ │ │ │ token │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼──────────────────┼───────┼────────┨ ┃ Docker Service Connector │ 🐳 docker │ 🐳 docker-registry │ password │ ✅ │ ✅ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼──────────────────┼───────┼────────┨ ┃ AWS Service Connector │ 🔶 aws │ 🔶 aws-generic │ implicit │ ✅ │ ✅ ┃ ┃ │ │ 📦 s3-bucket │ secret-key │ │ ┃ ┃ │ │ 🌀 kubernetes-cluster │ sts-token │ │ ┃ ┃ │ │ 🐳 docker-registry │ iam-role │ │ ┃ ┃ │ │ │ session-token │ │ ┃ ┃ │ │ │ federation-token │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼──────────────────┼───────┼────────┨ ┃ GCP Service Connector │ 🔵 gcp │ 🔵 gcp-generic │ implicit │ ✅ │ ✅ ┃ ┃ │ │ 📦 gcs-bucket │ user-account │ │ ┃ ┃ │ │ 🌀 kubernetes-cluster │ service-account │ │ ┃ ┃ │ │ 🐳 docker-registry │ oauth2-token │ │ ┃ ┃ │ │ │ impersonation │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼──────────────────┼───────┼────────┨ ┃ HyperAI Service Connector │ 🤖 hyperai │ 🤖 hyperai-instance │ rsa-key │ ✅ │ ✅ ┃ ┃ │ │ │ dsa-key │ │ ┃ ┃ │ │ │ ecdsa-key │ │ ┃ ┃ │ │ │ ed25519-key │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` {% endcode %} Service Connector Types are also displayed in the dashboard during the configuration of a new Service Connector: The cloud provider of choice for our example is AWS and we're looking to hook up an S3 bucket to an S3 Artifact Store Stack Component. We'll use the AWS Service Connector Type.
Interactive structured docs with Service Connector Types A lot more is hidden behind a Service Connector Type than a name and a simple list of resource types. Before using a Service Connector Type to configure a Service Connector, you probably need to understand what it is, what it can offer and what are the supported authentication methods and their requirements. All this can be accessed on-site directly through the CLI or in the dashboard. Some examples are included here. Showing information about the AWS Service Connector Type: ```sh zenml service-connector describe-type aws ``` {% code title="Example Command Output" %} ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ 🔶 AWS Service Connector (connector type: aws) ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Authentication methods: • 🔒 implicit • 🔒 secret-key • 🔒 sts-token • 🔒 iam-role • 🔒 session-token • 🔒 federation-token Resource types: • 🔶 aws-generic • 📦 s3-bucket • 🌀 kubernetes-cluster • 🐳 docker-registry Supports auto-configuration: True Available locally: True Available remotely: True The ZenML AWS Service Connector facilitates the authentication and access to managed AWS services and resources. These encompass a range of resources, including S3 buckets, ECR repositories, and EKS clusters. The connector provides support for various authentication methods, including explicit long-lived AWS secret keys, IAM roles, short-lived STS tokens and implicit authentication. To ensure heightened security measures, this connector also enables the generation of temporary STS security tokens that are scoped down to the minimum permissions necessary for accessing the intended resource. Furthermore, it includes automatic configuration and detection of credentials locally configured through the AWS CLI. This connector serves as a general means of accessing any AWS service by issuing pre-authenticated boto3 sessions to clients. Additionally, the connector can handle specialized authentication for S3, Docker and Kubernetes Python clients. It also allows for the configuration of local Docker and Kubernetes CLIs. The AWS Service Connector is part of the AWS ZenML integration. You can either install the entire integration or use a pypi extra to install it independently of the integration: • pip install "zenml[connectors-aws]" installs only prerequisites for the AWS Service Connector Type • zenml integration install aws installs the entire AWS ZenML integration It is not required to install and set up the AWS CLI on your local machine to use the AWS Service Connector to link Stack Components to AWS resources and services. However, it is recommended to do so if you are looking for a quick setup that includes using the auto-configuration Service Connector features. ──────────────────────────────────────────────────────────────────────────────── ``` {% endcode %} Dashboard equivalent: AWS Service Connector Type Details Fetching details about the S3 bucket resource type: ```sh zenml service-connector describe-type aws --resource-type s3-bucket ``` {% code title="Example Command Output" %} ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ 📦 AWS S3 bucket (resource type: s3-bucket) ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Authentication methods: implicit, secret-key, sts-token, iam-role, session-token, federation-token Supports resource instances: True Authentication methods: • 🔒 implicit • 🔒 secret-key • 🔒 sts-token • 🔒 iam-role • 🔒 session-token • 🔒 federation-token Allows users to connect to S3 buckets. When used by Stack Components, they are provided a pre-configured boto3 S3 client instance. The configured credentials must have at least the following AWS IAM permissions associated with the ARNs of S3 buckets that the connector will be allowed to access (e.g. arn:aws:s3:::* and arn:aws:s3:::*/* represent all the available S3 buckets). • s3:ListBucket • s3:GetObject • s3:PutObject • s3:DeleteObject • s3:ListAllMyBuckets • s3:GetBucketVersioning • s3:ListBucketVersions • s3:DeleteObjectVersion If set, the resource name must identify an S3 bucket using one of the following formats: • S3 bucket URI (canonical resource name): s3://{bucket-name} • S3 bucket ARN: arn:aws:s3:::{bucket-name} • S3 bucket name: {bucket-name} ──────────────────────────────────────────────────────────────────────────────── ``` {% endcode %} Dashboard equivalent: AWS Service Connector Type Details Displaying information about the AWS Session Token authentication method: ```sh zenml service-connector describe-type aws --auth-method session-token ``` {% code title="Example Command Output" %} ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ 🔒 AWS Session Token (auth method: session-token) ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Supports issuing temporary credentials: True Generates temporary session STS tokens for IAM users. The connector needs to be configured with an AWS secret key associated with an IAM user or AWS account root user (not recommended). The connector will generate temporary STS tokens upon request by calling the GetSessionToken STS API. These STS tokens have an expiration period longer that those issued through the AWS IAM Role authentication method and are more suitable for long-running processes that cannot automatically re-generate credentials upon expiration. An AWS region is required and the connector may only be used to access AWS resources in the specified region. The default expiration period for generated STS tokens is 12 hours with a minimum of 15 minutes and a maximum of 36 hours. Temporary credentials obtained by using the AWS account root user credentials (not recommended) have a maximum duration of 1 hour. As a precaution, when long-lived credentials (i.e. AWS Secret Keys) are detected on your environment by the Service Connector during auto-configuration, this authentication method is automatically chosen instead of the AWS Secret Key authentication method alternative. Generated STS tokens inherit the full set of permissions of the IAM user or AWS account root user that is calling the GetSessionToken API. Depending on your security needs, this may not be suitable for production use, as it can lead to accidental privilege escalation. Instead, it is recommended to use the AWS Federation Token or AWS IAM Role authentication methods to restrict the permissions of the generated STS tokens. For more information on session tokens and the GetSessionToken AWS API, see: the official AWS documentation on the subject. Attributes: • aws_access_key_id {string, secret, required}: AWS Access Key ID • aws_secret_access_key {string, secret, required}: AWS Secret Access Key • region {string, required}: AWS Region • endpoint_url {string, optional}: AWS Endpoint URL ──────────────────────────────────────────────────────────────────────────────── ``` {% endcode %} Dashboard equivalent: AWS Service Connector Type Details
Not all Stack Components support being linked to a Service Connector. This is indicated in the flavor description of each Stack Component. Our example uses the S3 Artifact Store, which does support it: ```sh $ zenml artifact-store flavor describe s3 Configuration class: S3ArtifactStoreConfig [...] This flavor supports connecting to external resources with a Service Connector. It requires a 's3-bucket' resource. You can get a list of all available connectors and the compatible resources that they can access by running: 'zenml service-connector list-resources --resource-type s3-bucket' If no compatible Service Connectors are yet registered, you can register a new one by running: 'zenml service-connector register -i' ``` The second step is _registering a Service Connector_ that effectively enables ZenML to authenticate to and access one or more remote resources. This step is best handled by someone with some infrastructure knowledge, but there are sane defaults and auto-detection mechanisms built into most Service Connectors that can make this a walk in the park even for the uninitiated. For our simple example, we're registering an AWS Service Connector with AWS credentials _automatically lifted up from your local host_, giving ZenML access to the same resources that you can access from your local machine through the AWS CLI. This step assumes the AWS CLI is already installed and set up with credentials on your machine (e.g. by running `aws configure`). ```sh zenml service-connector register aws-s3 --type aws --auto-configure --resource-type s3-bucket ``` {% code title="Example Command Output" %} ``` ⠼ Registering service connector 'aws-s3'... Successfully registered service connector `aws-s3` with access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼───────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ s3://zenbytes-bucket ┃ ┃ │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┃ │ s3://zenml-public-datasets ┃ ┃ │ s3://zenml-public-swagger-spec ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The CLI validates and shows all S3 buckets that can be accessed with the auto-discovered credentials. {% hint style="info" %} The ZenML CLI provides an interactive way of registering Service Connectors. Just use the `-i` command line argument and follow the interactive guide: ``` zenml service-connector register -i ``` {% endhint %}
What happens during auto-configuration A quick glance into the Service Connector configuration that was automatically detected gives a better idea of what happened: ```sh zenml service-connector describe aws-s3 ``` {% code title="Example Command Output" %} ``` Service connector 'aws-s3' of type 'aws' with id '96a92154-4ec7-4722-bc18-21eeeadb8a4f' is owned by user 'default' and is 'private'. 'aws-s3' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ ID │ 96a92154-4ec7-4722-bc18-21eeeadb8a4f ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ NAME │ aws-s3 ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ AUTH METHOD │ session-token ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ RESOURCE TYPES │ 📦 s3-bucket ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SECRET ID │ a8c6d0ff-456a-4b25-8557-f0d7e3c12c5f ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SESSION DURATION │ 43200s ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-15 18:45:17.822337 ┃ ┠──────────────────┼──────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-15 18:45:17.822341 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %} The AWS Service Connector discovered and lifted the AWS Secret Key that was configured on the local machine and securely stored it in the [Secrets Store](../../../getting-started/deploying-zenml/secret-management.md). Moreover, the following security best practice is automatically enforced by the AWS connector: the AWS Secret Key will be kept hidden on the ZenML Server and the clients will never use it directly to gain access to any AWS resources. Instead, the AWS Service Connector will generate short-lived security tokens and distribute those to clients. It will also take care of issuing new tokens when those expire. This is identifiable from the `session-token` authentication method and the session duration configuration attributes. One way to confirm this is to ask ZenML to show us the exact configuration that a Service Connector client would see, but this requires us to pick an S3 bucket for which temporary credentials can be generated: ```sh zenml service-connector describe aws-s3 --resource-id s3://zenfiles ``` {% code title="Example Command Output" %} ``` Service connector 'aws-s3 (s3-bucket | s3://zenfiles client)' of type 'aws' with id '96a92154-4ec7-4722-bc18-21eeeadb8a4f' is owned by user 'default' and is 'private'. 'aws-s3 (s3-bucket | s3://zenfiles client)' aws Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ ID │ 96a92154-4ec7-4722-bc18-21eeeadb8a4f ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ NAME │ aws-s3 (s3-bucket | s3://zenfiles client) ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ TYPE │ 🔶 aws ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ AUTH METHOD │ sts-token ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ RESOURCE TYPES │ 📦 s3-bucket ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ RESOURCE NAME │ s3://zenfiles ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ SECRET ID │ ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ EXPIRES IN │ 11h59m56s ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ OWNER │ default ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ SHARED │ ➖ ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ CREATED_AT │ 2023-06-15 18:56:33.880081 ┃ ┠──────────────────┼───────────────────────────────────────────┨ ┃ UPDATED_AT │ 2023-06-15 18:56:33.880082 ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────────┼───────────┨ ┃ region │ us-east-1 ┃ ┠───────────────────────┼───────────┨ ┃ aws_access_key_id │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_secret_access_key │ [HIDDEN] ┃ ┠───────────────────────┼───────────┨ ┃ aws_session_token │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━┛ ``` {% endcode %} As can be seen, this configuration is of a temporary STS AWS token that will expire in 12 hours. The AWS Secret Key is not visible on the client side.
The next step in this journey is _configuring and connecting one (or more) Stack Components to a remote resource_ via the Service Connector registered in the previous step. This is as easy as saying "_I want this S3 Artifact Store to use the `s3://my-bucket` S3 bucket_" and doesn't require any knowledge whatsoever about the authentication mechanisms or even the provenance of those resources. The following example creates an S3 Artifact store and connects it to an S3 bucket with the earlier connector: ```sh zenml artifact-store register s3-zenfiles --flavor s3 --path=s3://zenfiles zenml artifact-store connect s3-zenfiles --connector aws-s3 ``` {% code title="Example Command Output" %} ``` $ zenml artifact-store register s3-zenfiles --flavor s3 --path=s3://zenfiles Successfully registered artifact_store `s3-zenfiles`. $ zenml artifact-store connect s3-zenfiles --connector aws-s3 Successfully connected artifact store `s3-zenfiles` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────┼────────────────┨ ┃ 96a92154-4ec7-4722-bc18-21eeeadb8a4f │ aws-s3 │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} {% hint style="info" %} The ZenML CLI provides an even easier and more interactive way of connecting a stack component to an external resource. Just pass the `-i` command line argument and follow the interactive guide: ``` zenml artifact-store register s3-zenfiles --flavor s3 --path=s3://zenfiles zenml artifact-store connect s3-zenfiles -i ``` {% endhint %} The S3 Artifact Store Stack Component we just connected to the infrastructure is now ready to be used in a stack to run a pipeline: ```sh zenml stack register s3-zenfiles -o default -a s3-zenfiles --set ``` A simple pipeline could look like this: ```python from zenml import step, pipeline @step def simple_step_one() -> str: """Simple step one.""" return "Hello World!" @step def simple_step_two(msg: str) -> None: """Simple step two.""" print(msg) @pipeline def simple_pipeline() -> None: """Define single step pipeline.""" message = simple_step_one() simple_step_two(msg=message) if __name__ == "__main__": simple_pipeline() ``` Save this as `run.py` and run it with the following command: ```sh python run.py ``` {% code title="Example Command Output" %} ``` Running pipeline simple_pipeline on stack s3-zenfiles (caching enabled) Step simple_step_one has started. Step simple_step_one has finished in 1.065s. Step simple_step_two has started. Hello World! Step simple_step_two has finished in 5.681s. Pipeline run simple_pipeline-2023_06_15-19_29_42_159831 has finished in 12.522s. Dashboard URL: http://127.0.0.1:8237/default/pipelines/8267b0bc-9cbd-42ac-9b56-4d18275bdbb4/runs ``` {% endcode %} This example is just a simple demonstration of how to use Service Connectors to connect ZenML Stack Components to your infrastructure. The range of features and possibilities is much larger. ZenML ships with built-in Service Connectors able to connect and authenticate to AWS, GCP, and Azure and offers many different authentication methods and security best practices. Follow the resources below for more information.
🪄 The complete guide to Service ConnectorsEverything you need to know to unlock the power of Service Connectors in your project../service-connectors-guide.md
Security Best PracticesBest practices concerning the various authentication methods implemented by Service Connectors../best-security-practices.md
🐋 Docker Service ConnectorUse the Docker Service Connector to connect ZenML to a generic Docker container registry../docker-service-connector.md
🌀 Kubernetes Service ConnectorUse the Kubernetes Service Connector to connect ZenML to a generic Kubernetes cluster../kubernetes-service-connector.md
🔶 AWS Service ConnectorUse the AWS Service Connector to connect ZenML to AWS cloud resources../aws-service-connector.md
🔵 GCP Service ConnectorUse the GCP Service Connector to connect ZenML to GCP cloud resources../gcp-service-connector.md
🅰️ Azure Service ConnectorUse the Azure Service Connector to connect ZenML to Azure cloud resources../azure-service-connector.md
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/auth-management/service-connectors-guide.md ================ --- description: >- The complete guide to managing Service Connectors and connecting ZenML to external resources. --- # Service Connectors guide This documentation section contains everything that you need to use Service Connectors to connect ZenML to external resources. A lot of information is covered, so it might be useful to use the following guide to navigate it: * if you're only getting started with Service Connectors, we suggest starting by familiarizing yourself with the [terminology](service-connectors-guide.md#terminology). * check out the section on [Service Connector Types](service-connectors-guide.md#cloud-provider-service-connector-types) to understand the different Service Connector implementations that are available and when to use them. * jumping straight to the sections on [Registering Service Connectors](service-connectors-guide.md#register-service-connectors) can get you set up quickly if you are only looking for a quick way to evaluate Service Connectors and their features. * if all you need to do is connect a ZenML Stack Component to an external resource or service like a Kubernetes cluster, a Docker container registry, or an object storage bucket, and you already have some Service Connectors available, the section on [connecting Stack Components to resources](service-connectors-guide.md#connect-stack-components-to-resources) is all you need. In addition to this guide, there is an entire section dedicated to [best security practices concerning the various authentication methods](best-security-practices.md) implemented by Service Connectors, such as which types of credentials to use in development or production and how to keep your security information safe. That section is particularly targeted at engineers with some knowledge of infrastructure, but it should be accessible to larger audiences. ## Terminology As with any high-level abstraction, some terminology is needed to express the concepts and operations involved. In spite of the fact that Service Connectors cover such a large area of application as authentication and authorization for a variety of resources from a range of different vendors, we managed to keep this abstraction clean and simple. In the following expandable sections, you'll learn more about Service Connector Types, Resource Types, Resource Names, and Service Connectors.
Service Connector Types This term is used to represent and identify a particular Service Connector implementation and answer questions about its capabilities such as "what types of resources does this Service Connector give me access to", "what authentication methods does it support" and "what credentials and other information do I need to configure for it". This is analogous to the role Flavors play for Stack Components in that the Service Connector Type acts as the template from which one or more Service Connectors are created. For example, the built-in AWS Service Connector Type shipped with ZenML supports a rich variety of authentication methods and provides access to AWS resources such as S3 buckets, EKS clusters and ECR registries. The `zenml service-connector list-types` and `zenml service-connector describe-type` CLI commands can be used to explore the Service Connector Types available with your ZenML deployment. Extensive documentation is included covering supported authentication methods and Resource Types. The following are just some examples: ```sh zenml service-connector list-types ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ NAME │ TYPE │ RESOURCE TYPES │ AUTH METHODS │ LOCAL │ REMOTE ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ Kubernetes Service Connector │ 🌀 kubernetes │ 🌀 kubernetes-cluster │ password │ ✅ │ ✅ ┃ ┃ │ │ │ token │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ Docker Service Connector │ 🐳 docker │ 🐳 docker-registry │ password │ ✅ │ ✅ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ Azure Service Connector │ 🇦 azure │ 🇦 azure-generic │ implicit │ ✅ │ ✅ ┃ ┃ │ │ 📦 blob-container │ service-principal │ │ ┃ ┃ │ │ 🌀 kubernetes-cluster │ access-token │ │ ┃ ┃ │ │ 🐳 docker-registry │ │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ AWS Service Connector │ 🔶 aws │ 🔶 aws-generic │ implicit │ ✅ │ ✅ ┃ ┃ │ │ 📦 s3-bucket │ secret-key │ │ ┃ ┃ │ │ 🌀 kubernetes-cluster │ sts-token │ │ ┃ ┃ │ │ 🐳 docker-registry │ iam-role │ │ ┃ ┃ │ │ │ session-token │ │ ┃ ┃ │ │ │ federation-token │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ GCP Service Connector │ 🔵 gcp │ 🔵 gcp-generic │ implicit │ ✅ │ ✅ ┃ ┃ │ │ 📦 gcs-bucket │ user-account │ │ ┃ ┃ │ │ 🌀 kubernetes-cluster │ service-account │ │ ┃ ┃ │ │ 🐳 docker-registry │ oauth2-token │ │ ┃ ┃ │ │ │ impersonation │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector describe-type aws ``` {% code title="Example Command Output" %} ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ 🔶 AWS Service Connector (connector type: aws) ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Authentication methods: • 🔒 implicit • 🔒 secret-key • 🔒 sts-token • 🔒 iam-role • 🔒 session-token • 🔒 federation-token Resource types: • 🔶 aws-generic • 📦 s3-bucket • 🌀 kubernetes-cluster • 🐳 docker-registry Supports auto-configuration: True Available locally: True Available remotely: False The ZenML AWS Service Connector facilitates the authentication and access to managed AWS services and resources. These encompass a range of resources, including S3 buckets, ECR repositories, and EKS clusters. The connector provides support for various authentication methods, including explicit long-lived AWS secret keys, IAM roles, short-lived STS tokens and implicit authentication. To ensure heightened security measures, this connector also enables the generation of temporary STS security tokens that are scoped down to the minimum permissions necessary for accessing the intended resource. Furthermore, it includes automatic configuration and detection of credentials locally configured through the AWS CLI. This connector serves as a general means of accessing any AWS service by issuing pre-authenticated boto3 sessions to clients. Additionally, the connector can handle specialized authentication for S3, Docker and Kubernetes Python clients. It also allows for the configuration of local Docker and Kubernetes CLIs. The AWS Service Connector is part of the AWS ZenML integration. You can either install the entire integration or use a pypi extra to install it independently of the integration: • pip install "zenml[connectors-aws]" installs only prerequisites for the AWS Service Connector Type • zenml integration install aws installs the entire AWS ZenML integration It is not required to install and set up the AWS CLI on your local machine to use the AWS Service Connector to link Stack Components to AWS resources and services. However, it is recommended to do so if you are looking for a quick setup that includes using the auto-configuration Service Connector features. ──────────────────────────────────────────────────────────────────────────────── ``` {% endcode %} ```sh zenml service-connector describe-type aws --resource-type kubernetes-cluster ``` {% code title="Example Command Output" %} ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ 🌀 AWS EKS Kubernetes cluster (resource type: kubernetes-cluster) ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Authentication methods: implicit, secret-key, sts-token, iam-role, session-token, federation-token Supports resource instances: True Authentication methods: • 🔒 implicit • 🔒 secret-key • 🔒 sts-token • 🔒 iam-role • 🔒 session-token • 🔒 federation-token Allows users to access an EKS cluster as a standard Kubernetes cluster resource. When used by Stack Components, they are provided a pre-authenticated python-kubernetes client instance. The configured credentials must have at least the following AWS IAM permissions associated with the ARNs of EKS clusters that the connector will be allowed to access (e.g. arn:aws:eks:{region}:{account}:cluster/* represents all the EKS clusters available in the target AWS region). • eks:ListClusters • eks:DescribeCluster In addition to the above permissions, if the credentials are not associated with the same IAM user or role that created the EKS cluster, the IAM principal must be manually added to the EKS cluster's aws-auth ConfigMap, otherwise the Kubernetes client will not be allowed to access the cluster's resources. This makes it more challenging to use the AWS Implicit and AWS Federation Token authentication methods for this resource. For more information, see this documentation. If set, the resource name must identify an EKS cluster using one of the following formats: • EKS cluster name (canonical resource name): {cluster-name} • EKS cluster ARN: arn:aws:eks:{region}:{account}:cluster/{cluster-name} EKS cluster names are region scoped. The connector can only be used to access EKS clusters in the AWS region that it is configured to use. ──────────────────────────────────────────────────────────────────────────────── ``` {% endcode %} ```sh zenml service-connector describe-type aws --auth-method secret-key ``` {% code title="Example Command Output" %} ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ 🔒 AWS Secret Key (auth method: secret-key) ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Supports issuing temporary credentials: False Long-lived AWS credentials consisting of an AWS access key ID and secret access key associated with an AWS IAM user or AWS account root user (not recommended). This method is preferred during development and testing due to its simplicity and ease of use. It is not recommended as a direct authentication method for production use cases because the clients have direct access to long-lived credentials and are granted the full set of permissions of the IAM user or AWS account root user associated with the credentials. For production, it is recommended to use the AWS IAM Role, AWS Session Token or AWS Federation Token authentication method instead. An AWS region is required and the connector may only be used to access AWS resources in the specified region. If you already have the local AWS CLI set up with these credentials, they will be automatically picked up when auto-configuration is used. Attributes: • aws_access_key_id {string, secret, required}: AWS Access Key ID • aws_secret_access_key {string, secret, required}: AWS Secret Access Key • region {string, required}: AWS Region • endpoint_url {string, optional}: AWS Endpoint URL ──────────────────────────────────────────────────────────────────────────────── ``` {% endcode %}
Resource Types Resource Types are a way of organizing resources into logical, well-known classes based on the standard and/or protocol used to access them, or simply based on their vendor. This creates a unified language that can be used to declare the types of resources that are provided by Service Connectors on one hand and the types of resources that are required by Stack Components on the other hand. For example, we use the generic `kubernetes-cluster` resource type to refer to any and all Kubernetes clusters, since they are all generally accessible using the same standard libraries, clients and API regardless of whether they are Amazon EKS, Google GKE, Azure AKS or another flavor of managed or self-hosted deployment. Similarly, there is a generic `docker-registry` resource type that covers any and all container registries that implement the Docker/OCI interface, be it DockerHub, Amazon ECR, Google GCR, Azure ACR, K3D or something similar. Stack Components that need to connect to a Kubernetes cluster (e.g. the Kubernetes Orchestrator or the Seldon Model Deployer) can use the `kubernetes-cluster` resource type identifier to describe their resource requirements and remain agnostic of their vendor. The term Resource Type is used in ZenML everywhere resources accessible through Service Connectors are involved. For example, to list all Service Connector Types that can be used to broker access to Kubernetes Clusters, you can pass the `--resource-type` flag to the CLI command: ```sh zenml service-connector list-types --resource-type kubernetes-cluster ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ NAME │ TYPE │ RESOURCE TYPES │ AUTH METHODS │ LOCAL │ REMOTE ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ Kubernetes Service Connector │ 🌀 kubernetes │ 🌀 kubernetes-cluster │ password │ ✅ │ ✅ ┃ ┃ │ │ │ token │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ Azure Service Connector │ 🇦 azure │ 🇦 azure-generic │ implicit │ ✅ │ ✅ ┃ ┃ │ │ 📦 blob-container │ service-principal │ │ ┃ ┃ │ │ 🌀 kubernetes-cluster │ access-token │ │ ┃ ┃ │ │ 🐳 docker-registry │ │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ AWS Service Connector │ 🔶 aws │ 🔶 aws-generic │ implicit │ ✅ │ ✅ ┃ ┃ │ │ 📦 s3-bucket │ secret-key │ │ ┃ ┃ │ │ 🌀 kubernetes-cluster │ sts-token │ │ ┃ ┃ │ │ 🐳 docker-registry │ iam-role │ │ ┃ ┃ │ │ │ session-token │ │ ┃ ┃ │ │ │ federation-token │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ GCP Service Connector │ 🔵 gcp │ 🔵 gcp-generic │ implicit │ ✅ │ ✅ ┃ ┃ │ │ 📦 gcs-bucket │ user-account │ │ ┃ ┃ │ │ 🌀 kubernetes-cluster │ service-account │ │ ┃ ┃ │ │ 🐳 docker-registry │ oauth2-token │ │ ┃ ┃ │ │ │ impersonation │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` {% endcode %} From the above, you can see that there are not one but four Service Connector Types that can connect ZenML to Kubernetes clusters. The first one is a generic implementation that can be used with any standard Kubernetes cluster, including those that run on-premise. The other three deal exclusively with Kubernetes services managed by the AWS, GCP and Azure cloud providers. Conversely, to list all currently registered Service Connector instances that provide access to Kubernetes clusters, one might run: ```sh zenml service-connector list --resource_type kubernetes-cluster ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼───────────────────────┼──────────────────────────────┼───────────────┼───────────────────────┼──────────────────────────────┼────────┼─────────┼────────────┼─────────────────────┨ ┃ │ aws-iam-multi-eu │ e33c9fac-5daa-48b2-87bb-0187 │ 🔶 aws │ 🔶 aws-generic │ │ ➖ │ default │ │ region:eu-central-1 ┃ ┃ │ │ d3782cde │ │ 📦 s3-bucket │ │ │ │ │ ┃ ┃ │ │ │ │ 🌀 kubernetes-cluster │ │ │ │ │ ┃ ┃ │ │ │ │ 🐳 docker-registry │ │ │ │ │ ┃ ┠────────┼───────────────────────┼──────────────────────────────┼───────────────┼───────────────────────┼──────────────────────────────┼────────┼─────────┼────────────┼─────────────────────┨ ┃ │ aws-iam-multi-us │ ed528d5a-d6cb-4fc4-bc52-c3d2 │ 🔶 aws │ 🔶 aws-generic │ │ ➖ │ default │ │ region:us-east-1 ┃ ┃ │ │ d01643e5 │ │ 📦 s3-bucket │ │ │ │ │ ┃ ┃ │ │ │ │ 🌀 kubernetes-cluster │ │ │ │ │ ┃ ┃ │ │ │ │ 🐳 docker-registry │ │ │ │ │ ┃ ┠────────┼───────────────────────┼──────────────────────────────┼───────────────┼───────────────────────┼──────────────────────────────┼────────┼─────────┼────────────┼─────────────────────┨ ┃ │ kube-auto │ da497715-7502-4cdd-81ed-289e │ 🌀 kubernetes │ 🌀 kubernetes-cluster │ A5F8F4142FB12DDCDE9F21F6E9B0 │ ➖ │ default │ │ ┃ ┃ │ │ 70664597 │ │ │ 7A18.gr7.us-east-1.eks.amazo │ │ │ │ ┃ ┃ │ │ │ │ │ naws.com │ │ │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
Resource Names (also known as Resource IDs) If a Resource Type is used to identify a class of resources, we also need some way to uniquely identify each resource instance belonging to that class that a Service Connector can provide access to. For example, an AWS Service Connector can be configured to provide access to multiple S3 buckets identifiable by their bucket names or their `s3://bucket-name` formatted URIs. Similarly, an AWS Service Connector can be configured to provide access to multiple EKS Kubernetes clusters in the same AWS region, each uniquely identifiable by their EKS cluster name. This is what we call Resource Names. Resource Names make it generally easy to identify a particular resource instance accessible through a Service Connector, especially when used together with the Service Connector name and the Resource Type. The following ZenML CLI command output shows a few examples featuring Resource Names for S3 buckets, EKS clusters, ECR registries and general Kubernetes clusters. As you can see, the way we name resources varies from implementation to implementation and resource type to resource type: ```sh zenml service-connector list-resources ``` {% code title="Example Command Output" %} ``` The following resources can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼──────────────────────────────────────────────────────────────────┨ ┃ 8d307b98-f125-4d7a-b5d5-924c07ba04bb │ aws-session-docker │ 🔶 aws │ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼──────────────────────────────────────────────────────────────────┨ ┃ d1e5ecf5-1531-4507-bbf5-be0a114907a5 │ aws-session-s3 │ 🔶 aws │ 📦 s3-bucket │ s3://public-flavor-logos ┃ ┃ │ │ │ │ s3://sagemaker-us-east-1-715803424590 ┃ ┃ │ │ │ │ s3://spark-artifact-store ┃ ┃ │ │ │ │ s3://spark-demo-as ┃ ┃ │ │ │ │ s3://spark-demo-dataset ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼──────────────────────────────────────────────────────────────────┨ ┃ d2341762-28a3-4dfc-98b9-1ae9aaa93228 │ aws-key-docker-eu │ 🔶 aws │ 🐳 docker-registry │ 715803424590.dkr.ecr.eu-central-1.amazonaws.com ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼──────────────────────────────────────────────────────────────────┨ ┃ 0658a465-2921-4d6b-a495-2dc078036037 │ aws-key-kube-zenhacks │ 🔶 aws │ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼──────────────────────────────────────────────────────────────────┨ ┃ 049e7f5e-e14c-42b7-93d4-a273ef414e66 │ eks-eu-central-1 │ 🔶 aws │ 🌀 kubernetes-cluster │ kubeflowmultitenant ┃ ┃ │ │ │ │ zenbox ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼──────────────────────────────────────────────────────────────────┨ ┃ b551f3ae-1448-4f36-97a2-52ce303f20c9 │ kube-auto │ 🌀 kubernetes │ 🌀 kubernetes-cluster │ A5F8F4142FB12DDCDE9F21F6E9B07A18.gr7.us-east-1.eks.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} Every Service Connector Type defines its own rules for how Resource Names are formatted. These rules are documented in the section belonging each resource type. For example: ```sh zenml service-connector describe-type aws --resource-type docker-registry ``` {% code title="Example Command Output" %} ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ 🐳 AWS ECR container registry (resource type: docker-registry) ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Authentication methods: implicit, secret-key, sts-token, iam-role, session-token, federation-token Supports resource instances: False Authentication methods: • 🔒 implicit • 🔒 secret-key • 🔒 sts-token • 🔒 iam-role • 🔒 session-token • 🔒 federation-token Allows users to access one or more ECR repositories as a standard Docker registry resource. When used by Stack Components, they are provided a pre-authenticated python-docker client instance. The configured credentials must have at least the following AWS IAM permissions associated with the ARNs of one or more ECR repositories that the connector will be allowed to access (e.g. arn:aws:ecr:{region}:{account}:repository/* represents all the ECR repositories available in the target AWS region). • ecr:DescribeRegistry • ecr:DescribeRepositories • ecr:ListRepositories • ecr:BatchGetImage • ecr:DescribeImages • ecr:BatchCheckLayerAvailability • ecr:GetDownloadUrlForLayer • ecr:InitiateLayerUpload • ecr:UploadLayerPart • ecr:CompleteLayerUpload • ecr:PutImage • ecr:GetAuthorizationToken This resource type is not scoped to a single ECR repository. Instead, a connector configured with this resource type will grant access to all the ECR repositories that the credentials are allowed to access under the configured AWS region (i.e. all repositories under the Docker registry URL https://{account-id}.dkr.ecr.{region}.amazonaws.com). The resource name associated with this resource type uniquely identifies an ECR registry using one of the following formats (the repository name is ignored, only the registry URL/ARN is used): • ECR repository URI (canonical resource name): [https://]{account}.dkr.ecr.{region}.amazonaws.com[/{repository-name}] • ECR repository ARN: arn:aws:ecr:{region}:{account-id}:repository[/{repository-name}] ECR repository names are region scoped. The connector can only be used to access ECR repositories in the AWS region that it is configured to use. ──────────────────────────────────────────────────────────────────────────────── ``` {% endcode %}
Service Connectors The Service Connector is how you configure ZenML to authenticate and connect to one or more external resources. It stores the required configuration and security credentials and can optionally be scoped with a Resource Type and a Resource Name. Depending on the Service Connector Type implementation, a Service Connector instance can be configured in one of the following modes with regards to the types and number of resources that it has access to: * a **multi-type** Service Connector instance that can be configured once and used to gain access to multiple types of resources. This is only possible with Service Connector Types that support multiple Resource Types to begin with, such as those that target multi-service cloud providers like AWS, GCP and Azure. In contrast, a **single-type** Service Connector can only be used with a single Resource Type. To configure a multi-type Service Connector, you can simply skip scoping its Resource Type during registration. * a **multi-instance** Service Connector instance can be configured once and used to gain access to multiple resources of the same type, each identifiable by a Resource Name. Not all types of connectors and not all types of resources support multiple instances. Some Service Connectors Types like the generic Kubernetes and Docker connector types only allow **single-instance** configurations: a Service Connector instance can only be used to access a single Kubernetes cluster and a single Docker registry. To configure a multi-instance Service Connector, you can simply skip scoping its Resource Name during registration. The following is an example of configuring a multi-type AWS Service Connector instance capable of accessing multiple AWS resources of different types: ```sh zenml service-connector register aws-multi-type --type aws --auto-configure ``` {% code title="Example Command Output" %} ``` ⠋ Registering service connector 'aws-multi-type'... Successfully registered service connector `aws-multi-type` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┃ │ s3://zenml-public-datasets ┃ ┃ │ s3://zenml-public-swagger-spec ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The following is an example of configuring a multi-instance AWS S3 Service Connector instance capable of accessing multiple AWS S3 buckets: ```sh zenml service-connector register aws-s3-multi-instance --type aws --auto-configure --resource-type s3-bucket ``` {% code title="Example Command Output" %} ``` ⠸ Registering service connector 'aws-s3-multi-instance'... Successfully registered service connector `aws-s3-multi-instance` with access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼───────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┃ │ s3://zenml-public-datasets ┃ ┃ │ s3://zenml-public-swagger-spec ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The following is an example of configuring a single-instance AWS S3 Service Connector instance capable of accessing a single AWS S3 bucket: ```sh zenml service-connector register aws-s3-zenfiles --type aws --auto-configure --resource-type s3-bucket --resource-id s3://zenfiles ``` {% code title="Example Command Output" %} ``` ⠼ Registering service connector 'aws-s3-zenfiles'... Successfully registered service connector `aws-s3-zenfiles` with access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
## Explore Service Connector Types Service Connector Types are not only templates used to instantiate Service Connectors, they also form a body of knowledge that documents best security practices and guides users through the complicated world of authentication and authorization. ZenML ships with a handful of Service Connector Types that enable you right out-of-the-box to connect ZenML to cloud resources and services available from cloud providers such as AWS and GCP, as well as on-premise infrastructure. In addition to built-in Service Connector Types, ZenML can be easily extended with custom Service Connector implementations. To discover the Connector Types available with your ZenML deployment, you can use the `zenml service-connector list-types` CLI command: ```sh zenml service-connector list-types ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┯━━━━━━━┯━━━━━━━━┓ ┃ NAME │ TYPE │ RESOURCE TYPES │ AUTH METHODS │ LOCAL │ REMOTE ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ Kubernetes Service Connector │ 🌀 kubernetes │ 🌀 kubernetes-cluster │ password │ ✅ │ ✅ ┃ ┃ │ │ │ token │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ Docker Service Connector │ 🐳 docker │ 🐳 docker-registry │ password │ ✅ │ ✅ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ Azure Service Connector │ 🇦 azure │ 🇦 azure-generic │ implicit │ ✅ │ ✅ ┃ ┃ │ │ 📦 blob-container │ service-principal │ │ ┃ ┃ │ │ 🌀 kubernetes-cluster │ access-token │ │ ┃ ┃ │ │ 🐳 docker-registry │ │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ AWS Service Connector │ 🔶 aws │ 🔶 aws-generic │ implicit │ ✅ │ ✅ ┃ ┃ │ │ 📦 s3-bucket │ secret-key │ │ ┃ ┃ │ │ 🌀 kubernetes-cluster │ sts-token │ │ ┃ ┃ │ │ 🐳 docker-registry │ iam-role │ │ ┃ ┃ │ │ │ session-token │ │ ┃ ┃ │ │ │ federation-token │ │ ┃ ┠──────────────────────────────┼───────────────┼───────────────────────┼───────────────────┼───────┼────────┨ ┃ GCP Service Connector │ 🔵 gcp │ 🔵 gcp-generic │ implicit │ ✅ │ ✅ ┃ ┃ │ │ 📦 gcs-bucket │ user-account │ │ ┃ ┃ │ │ 🌀 kubernetes-cluster │ service-account │ │ ┃ ┃ │ │ 🐳 docker-registry │ oauth2-token │ │ ┃ ┃ │ │ │ impersonation │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━┷━━━━━━━━┛ ``` {% endcode %}
Exploring the documentation embedded into Service Connector Types A lot more is hidden behind a Service Connector Type than a name and a simple list of resource types. Before using a Service Connector Type to configure a Service Connector, you probably need to understand what it is, what it can offer and what are the supported authentication methods and their requirements. All this can be accessed directly through the CLI. Some examples are included here. Showing information about the `gcp` Service Connector Type: ```sh zenml service-connector describe-type gcp ``` {% code title="Example Command Output" %} ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ 🔵 GCP Service Connector (connector type: gcp) ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Authentication methods: • 🔒 implicit • 🔒 user-account • 🔒 service-account • 🔒 oauth2-token • 🔒 impersonation Resource types: • 🔵 gcp-generic • 📦 gcs-bucket • 🌀 kubernetes-cluster • 🐳 docker-registry Supports auto-configuration: True Available locally: True Available remotely: True The ZenML GCP Service Connector facilitates the authentication and access to managed GCP services and resources. These encompass a range of resources, including GCS buckets, GCR container repositories and GKE clusters. The connector provides support for various authentication methods, including GCP user accounts, service accounts, short-lived OAuth 2.0 tokens and implicit authentication. To ensure heightened security measures, this connector always issues short-lived OAuth 2.0 tokens to clients instead of long-lived credentials. Furthermore, it includes automatic configuration and detection of credentials locally configured through the GCP CLI. This connector serves as a general means of accessing any GCP service by issuing OAuth 2.0 credential objects to clients. Additionally, the connector can handle specialized authentication for GCS, Docker and Kubernetes Python clients. It also allows for the configuration of local Docker and Kubernetes CLIs. The GCP Service Connector is part of the GCP ZenML integration. You can either install the entire integration or use a pypi extra to install it independently of the integration: • pip install "zenml[connectors-gcp]" installs only prerequisites for the GCP Service Connector Type • zenml integration install gcp installs the entire GCP ZenML integration It is not required to install and set up the GCP CLI on your local machine to use the GCP Service Connector to link Stack Components to GCP resources and services. However, it is recommended to do so if you are looking for a quick setup that includes using the auto-configuration Service Connector features. ────────────────────────────────────────────────────────────────────────────────── ``` {% endcode %} Fetching details about the GCP `kubernetes-cluster` resource type (i.e. the GKE cluster): ```sh zenml service-connector describe-type gcp --resource-type kubernetes-cluster ``` {% code title="Example Command Output" %} ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ 🌀 GCP GKE Kubernetes cluster (resource type: kubernetes-cluster) ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Authentication methods: implicit, user-account, service-account, oauth2-token, impersonation Supports resource instances: True Authentication methods: • 🔒 implicit • 🔒 user-account • 🔒 service-account • 🔒 oauth2-token • 🔒 impersonation Allows Stack Components to access a GKE registry as a standard Kubernetes cluster resource. When used by Stack Components, they are provided a pre-authenticated Python Kubernetes client instance. The configured credentials must have at least the following GCP permissions associated with the GKE clusters that it can access: • container.clusters.list • container.clusters.get In addition to the above permissions, the credentials should include permissions to connect to and use the GKE cluster (i.e. some or all permissions in the Kubernetes Engine Developer role). If set, the resource name must identify an GKE cluster using one of the following formats: • GKE cluster name: {cluster-name} GKE cluster names are project scoped. The connector can only be used to access GKE clusters in the GCP project that it is configured to use. ──────────────────────────────────────────────────────────────────────────────── ``` {% endcode %} Displaying information about the `service-account` GCP authentication method: ```sh zenml service-connector describe-type gcp --auth-method service-account ``` {% code title="Example Command Output" %} ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ 🔒 GCP Service Account (auth method: service-account) ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Supports issuing temporary credentials: False Use a GCP service account and its credentials to authenticate to GCP services. This method requires a GCP service account and a service account key JSON created for it. The GCP connector generates temporary OAuth 2.0 tokens from the user account credentials and distributes them to clients. The tokens have a limited lifetime of 1 hour. A GCP project is required and the connector may only be used to access GCP resources in the specified project. If you already have the GOOGLE_APPLICATION_CREDENTIALS environment variable configured to point to a service account key JSON file, it will be automatically picked up when auto-configuration is used. Attributes: • service_account_json {string, secret, required}: GCP Service Account Key JSON • project_id {string, required}: GCP Project ID where the target resource is located. ──────────────────────────────────────────────────────────────────────────────── ``` {% endcode %}
### Basic Service Connector Types Service Connector Types like the [Kubernetes Service Connector](kubernetes-service-connector.md) and [Docker Service Connector](docker-service-connector.md) can only handle one resource at a time: a Kubernetes cluster and a Docker container registry respectively. These basic Service Connector Types are the easiest to instantiate and manage, as each Service Connector instance is tied exactly to one resource (i.e. they are _single-instance_ connectors). The following output shows two Service Connector instances configured from basic Service Connector Types: * a Docker Service Connector that grants authenticated access to the DockerHub registry and allows pushing/pulling images that are stored in private repositories belonging to a DockerHub account * a Kubernetes Service Connector that authenticates access to a Kubernetes cluster running on-premise and allows managing containerized workloads running there. ``` $ zenml service-connector list ┏━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼────────────────┼──────────────────────────────────────┼───────────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ dockerhub │ b485626e-7fee-4525-90da-5b26c72331eb │ 🐳 docker │ 🐳 docker-registry │ docker.io │ ➖ │ default │ │ ┃ ┠────────┼────────────────┼──────────────────────────────────────┼───────────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ kube-on-prem │ 4315e8eb-fcbd-4938-a4d7-a9218ab372a1 │ 🌀 kubernetes │ 🌀 kubernetes-cluster │ 192.168.0.12 │ ➖ │ default │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┛ ``` ### Cloud provider Service Connector Types Cloud service providers like AWS, GCP and Azure implement one or more authentication schemes that are unified across a wide range or resources and services, all managed under the same umbrella. This allows users to access many different resources with a single set of authentication credentials. Some authentication methods are straightforward to set up, but are only meant to be used for development and testing. Other authentication schemes are powered by extensive roles and permissions management systems and are targeted at production environments where security and operations at scale are big concerns. The corresponding cloud provider Service Connector Types are designed accordingly: * they support multiple types of resources (e.g. Kubernetes clusters, Docker registries, a form of object storage) * they usually include some form of "generic" Resource Type that can be used by clients to access types of resources that are not yet part of the supported set. When this generic Resource Type is used, clients and Stack Components that access the connector are provided some form of generic session, credentials or client that can be used to access any of the cloud provider resources. For example, in the AWS case, clients accessing the `aws-generic` Resource Type are issued a pre-authenticated `boto3` Session object that can be used to access any AWS service. * they support multiple authentication methods. Some of these allow clients direct access to long-lived, broad-access credentials and are only recommended for local development use. Others support distributing temporary API tokens automatically generated from long-lived credentials, which are safer for production use-cases, but may be more difficult to set up. A few authentication methods even support down-scoping the permissions of temporary API tokens so that they only allow access to the target resource and restrict access to everything else. This is covered at length [in the section on best practices for authentication methods](service-connectors-guide.md). * there is flexibility regarding the range of resources that a single cloud provider Service Connector instance configured with a single set of credentials can be scoped to access: * a _multi-type Service Connector_ instance can access any type of resources from the range of supported Resource Types * a _multi-instance Service Connector_ instance can access multiple resources of the same type * a _single-instance Service Connector_ instance is scoped to access a single resource The following output shows three different Service Connectors configured from the same GCP Service Connector Type using three different scopes but with the same credentials: * a multi-type GCP Service Connector that allows access to every possible resource accessible with the configured credentials * a multi-instance GCS Service Connector that allows access to multiple GCS buckets * a single-instance GCS Service Connector that only permits access to one GCS bucket ``` $ zenml service-connector list ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼────────────────────────┼──────────────────────────────────────┼────────┼───────────────────────┼─────────────────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ gcp-multi │ 9d953320-3560-4a78-817c-926a3898064d │ 🔵 gcp │ 🔵 gcp-generic │ │ ➖ │ default │ │ ┃ ┃ │ │ │ │ 📦 gcs-bucket │ │ │ │ │ ┃ ┃ │ │ │ │ 🌀 kubernetes-cluster │ │ │ │ │ ┃ ┃ │ │ │ │ 🐳 docker-registry │ │ │ │ │ ┃ ┠────────┼────────────────────────┼──────────────────────────────────────┼────────┼───────────────────────┼─────────────────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ gcs-multi │ ff9c0723-7451-46b7-93ef-fcf3efde30fa │ 🔵 gcp │ 📦 gcs-bucket │ │ ➖ │ default │ │ ┃ ┠────────┼────────────────────────┼──────────────────────────────────────┼────────┼───────────────────────┼─────────────────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ gcs-langchain-slackbot │ cf3953e9-414c-4875-ba00-24c62a0dc0c5 │ 🔵 gcp │ 📦 gcs-bucket │ gs://langchain-slackbot │ ➖ │ default │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┛ ``` ### Local and remote availability {% hint style="success" %} You only need to be aware of local and remote availability for Service Connector Types if you are explicitly looking to use a Service Connector Type without installing its package prerequisites or if you are implementing or using a custom Service Connector Type implementation with your ZenML deployment. In all other cases, you may safely ignore this section. {% endhint %} The `LOCAL` and `REMOTE` flags in the `zenml service-connector list-types` output indicate if the Service Connector implementation is available locally (i.e. where the ZenML client and pipelines are running) and remotely (i.e. where the ZenML server is running). {% hint style="info" %} All built-in Service Connector Types are by default available on the ZenML server, but some built-in Service Connector Types require additional Python packages to be installed to be available in your local environment. See the section documenting each Service Connector Type to find what these prerequisites are and how to install them. {% endhint %} The local/remote availability determines the possible actions and operations that can be performed with a Service Connector. The following are possible with a Service Connector Type that is available either locally or remotely: * Service Connector registration, update, and discovery (i.e. the `zenml service-connector register`, `zenml service-connector update`, `zenml service-connector list` and `zenml service-connector describe` CLI commands). * Service Connector verification: checking whether its configuration and credentials are valid and can be actively used to access the remote resources (i.e. the `zenml service-connector verify` CLI commands). * Listing the resources that can be accessed through a Service Connector (i.e. the `zenml service-connector verify` and `zenml service-connector list-resources` CLI commands) * Connecting a Stack Component to a remote resource via a Service Connector The following operations are only possible with Service Connector Types that are locally available (with some notable exceptions covered in the information box that follows): * Service Connector auto-configuration and discovery of credentials stored by a local client, CLI, or SDK (e.g. aws or kubectl). * Using the configuration and credentials managed by a Service Connector to configure a local client, CLI, or SDK (e.g. docker or kubectl). * Running pipelines with a Stack Component that is connected to a remote resource through a Service Connector {% hint style="info" %} One interesting and useful byproduct of the way cloud provider Service Connectors are designed is the fact that you don't need to have the cloud provider Service Connector Type available client-side to be able to access some of its resources. Take the following situation for example: * the GCP Service Connector Type can provide access to GKE Kubernetes clusters and GCR Docker container registries. * however, you don't need the GCP Service Connector Type or any GCP libraries to be installed on the ZenML clients to connect to and use those Kubernetes clusters or Docker registries in your ML pipelines. * the Kubernetes Service Connector Type is enough to access any Kubernetes cluster, regardless of its provenance (AWS, GCP, etc.) * the Docker Service Connector Type is enough to access any Docker container registry, regardless of its provenance (AWS, GCP, etc.) {% endhint %} ## Register Service Connectors When you reach this section, you probably already made up your mind about the type of infrastructure or cloud provider that you want to use to run your ZenML pipelines after reading through [the Service Connector Types section](service-connectors-guide.md#explore-service-connector-types), and you probably carefully weighed your [choices of authentication methods and best security practices](best-security-practices.md). Either that or you simply want to quickly try out a Service Connector to [connect one of the ZenML Stack components to an external resource](service-connectors-guide.md#connect-stack-components-to-resources). If you are looking for a quick, assisted tour, we recommend using the interactive CLI mode to configure Service Connectors, especially if this is your first time doing it: ``` zenml service-connector register -i ```
Interactive Service Connector registration example ```sh zenml service-connector register -i ``` {% code title="Example Command Output" %} ``` Please enter a name for the service connector: gcp-interactive Please enter a description for the service connector []: Interactive GCP connector example ╔══════════════════════════════════════════════════════════════════════════════╗ ║ Available service connector types ║ ╚══════════════════════════════════════════════════════════════════════════════╝ 🌀 Kubernetes Service Connector (connector type: kubernetes) Authentication methods: • 🔒 password • 🔒 token Resource types: • 🌀 kubernetes-cluster Supports auto-configuration: True Available locally: True Available remotely: True This ZenML Kubernetes service connector facilitates authenticating and connecting to a Kubernetes cluster. The connector can be used to access to any generic Kubernetes cluster by providing pre-authenticated Kubernetes python clients to Stack Components that are linked to it and also allows configuring the local Kubernetes CLI (i.e. kubectl). The Kubernetes Service Connector is part of the Kubernetes ZenML integration. You can either install the entire integration or use a pypi extra to install it independently of the integration: • pip install "zenml[connectors-kubernetes]" installs only prerequisites for the Kubernetes Service Connector Type • zenml integration install kubernetes installs the entire Kubernetes ZenML integration A local Kubernetes CLI (i.e. kubectl ) and setting up local kubectl configuration contexts is not required to access Kubernetes clusters in your Stack Components through the Kubernetes Service Connector. 🐳 Docker Service Connector (connector type: docker) Authentication methods: • 🔒 password Resource types: • 🐳 docker-registry Supports auto-configuration: False Available locally: True Available remotely: True The ZenML Docker Service Connector allows authenticating with a Docker or OCI container registry and managing Docker clients for the registry. This connector provides pre-authenticated python-docker Python clients to Stack Components that are linked to it. No Python packages are required for this Service Connector. All prerequisites are included in the base ZenML Python package. Docker needs to be installed on environments where container images are built and pushed to the target container registry. [...] ──────────────────────────────────────────────────────────────────────────────── Please select a service connector type (kubernetes, docker, azure, aws, gcp): gcp ╔══════════════════════════════════════════════════════════════════════════════╗ ║ Available resource types ║ ╚══════════════════════════════════════════════════════════════════════════════╝ 🔵 Generic GCP resource (resource type: gcp-generic) Authentication methods: implicit, user-account, service-account, oauth2-token, impersonation Supports resource instances: False Authentication methods: • 🔒 implicit • 🔒 user-account • 🔒 service-account • 🔒 oauth2-token • 🔒 impersonation This resource type allows Stack Components to use the GCP Service Connector to connect to any GCP service or resource. When used by Stack Components, they are provided a Python google-auth credentials object populated with a GCP OAuth 2.0 token. This credentials object can then be used to create GCP Python clients for any particular GCP service. This generic GCP resource type is meant to be used with Stack Components that are not represented by other, more specific resource type, like GCS buckets, Kubernetes clusters or Docker registries. For example, it can be used with the Google Cloud Builder Image Builder stack component, or the Vertex AI Orchestrator and Step Operator. It should be accompanied by a matching set of GCP permissions that allow access to the set of remote resources required by the client and Stack Component. The resource name represents the GCP project that the connector is authorized to access. 📦 GCP GCS bucket (resource type: gcs-bucket) Authentication methods: implicit, user-account, service-account, oauth2-token, impersonation Supports resource instances: True Authentication methods: • 🔒 implicit • 🔒 user-account • 🔒 service-account • 🔒 oauth2-token • 🔒 impersonation Allows Stack Components to connect to GCS buckets. When used by Stack Components, they are provided a pre-configured GCS Python client instance. The configured credentials must have at least the following GCP permissions associated with the GCS buckets that it can access: • storage.buckets.list • storage.buckets.get • storage.objects.create • storage.objects.delete • storage.objects.get • storage.objects.list • storage.objects.update For example, the GCP Storage Admin role includes all of the required permissions, but it also includes additional permissions that are not required by the connector. If set, the resource name must identify a GCS bucket using one of the following formats: • GCS bucket URI: gs://{bucket-name} • GCS bucket name: {bucket-name} [...] ──────────────────────────────────────────────────────────────────────────────── Please select a resource type or leave it empty to create a connector that can be used to access any of the supported resource types (gcp-generic, gcs-bucket, kubernetes-cluster, docker-registry). []: gcs-bucket Would you like to attempt auto-configuration to extract the authentication configuration from your local environment ? [y/N]: y Service connector auto-configured successfully with the following configuration: Service connector 'gcp-interactive' of type 'gcp' is 'private'. 'gcp-interactive' gcp Service Connector Details ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠──────────────────┼─────────────────┨ ┃ NAME │ gcp-interactive ┃ ┠──────────────────┼─────────────────┨ ┃ TYPE │ 🔵 gcp ┃ ┠──────────────────┼─────────────────┨ ┃ AUTH METHOD │ user-account ┃ ┠──────────────────┼─────────────────┨ ┃ RESOURCE TYPES │ 📦 gcs-bucket ┃ ┠──────────────────┼─────────────────┨ ┃ RESOURCE NAME │ ┃ ┠──────────────────┼─────────────────┨ ┃ SESSION DURATION │ N/A ┃ ┠──────────────────┼─────────────────┨ ┃ EXPIRES IN │ N/A ┃ ┠──────────────────┼─────────────────┨ ┃ SHARED │ ➖ ┃ ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┛ Configuration ┏━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┓ ┃ PROPERTY │ VALUE ┃ ┠───────────────────┼────────────┨ ┃ project_id │ zenml-core ┃ ┠───────────────────┼────────────┨ ┃ user_account_json │ [HIDDEN] ┃ ┗━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┛ No labels are set for this service connector. The service connector configuration has access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼─────────────────────────────────────────────────┨ ┃ 📦 gcs-bucket │ gs://annotation-gcp-store ┃ ┃ │ gs://zenml-bucket-sl ┃ ┃ │ gs://zenml-core.appspot.com ┃ ┃ │ gs://zenml-core_cloudbuild ┃ ┃ │ gs://zenml-datasets ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ Would you like to continue with the auto-discovered configuration or switch to manual ? (auto, manual) [auto]: The following GCP GCS bucket instances are reachable through this connector: - gs://annotation-gcp-store - gs://zenml-bucket-sl - gs://zenml-core.appspot.com - gs://zenml-core_cloudbuild - gs://zenml-datasets Please select one or leave it empty to create a connector that can be used to access any of them []: gs://zenml-datasets Successfully registered service connector `gcp-interactive` with access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼─────────────────────┨ ┃ 📦 gcs-bucket │ gs://zenml-datasets ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
Regardless of how you came here, you should already have some idea of the following: * the type of resources that you want to connect ZenML to. This may be a Kubernetes cluster, a Docker container registry or an object storage service like AWS S3 or GCS. * the Service Connector implementation (i.e. Service Connector Type) that you want to use to connect to those resources. This could be one of the cloud provider Service Connector Types like AWS and GCP that provide access to a broader range of services, or one of the basic Service Connector Types like Kubernetes or Docker that only target a specific resource. * the credentials and authentication method that you want to use Other questions that should be answered in this section: * are you just looking to connect a ZenML Stack Component to a single resource? or would you rather configure a wide-access ZenML Service Connector that gives ZenML and all its users access to a broader range of resource types and resource instances with a single set of credentials issued by your cloud provider? * have you already provisioned all the authentication prerequisites (e.g. service accounts, roles, permissions) and prepared the credentials you will need to configure the Service Connector? If you already have one of the cloud provider CLIs configured with credentials on your local host, you can easily use the Service Connector auto-configuration capabilities to get faster where you need to go. For help answering these questions, you can also use the interactive CLI mode to register Service Connectors and/or consult the documentation dedicated to each individual Service Connector Type. ### Auto-configuration Many Service Connector Types support using auto-configuration to discover and extract configuration information and credentials directly from your local environment. This assumes that you have already installed and set up the local CLI or SDK associated with the type of resource or cloud provider that you're willing to use. The Service Connector auto-configuration feature relies on these CLIs being configured with valid credentials to work properly. Some examples are listed here, but you should consult the documentation section for the Service Connector Type of choice to find out if and how auto-configuration is supported: * AWS uses the [`aws configure` CLI command](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) * GCP offers [the `gcloud auth application-default login` CLI command](https://cloud.google.com/docs/authentication/provide-credentials-adc#how\_to\_provide\_credentials\_to\_adc) * Azure provides [the `az login` CLI command](https://learn.microsoft.com/en-us/cli/azure/authenticate-azure-cli)
Or simply try it and find out ```sh zenml service-connector register kubernetes-auto --type kubernetes --auto-configure ``` {% code title="Example Command Output" %} ``` Successfully registered service connector `kubernetes-auto` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼────────────────┨ ┃ 🌀 kubernetes-cluster │ 35.185.95.223 ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector register aws-auto --type aws --auto-configure ``` {% code title="Example Command Output" %} ``` ⠼ Registering service connector 'aws-auto'... Successfully registered service connector `aws-auto` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector register gcp-auto --type gcp --auto-configure ``` {% code title="Example Command Output" %} ``` Successfully registered service connector `gcp-auto` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🔵 gcp-generic │ zenml-core ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 📦 gcs-bucket │ gs://annotation-gcp-store ┃ ┃ │ 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 ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┠───────────────────────┼─────────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ gcr.io/zenml-core ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
### Scopes: multi-type, multi-instance, and single-instance These terms are briefly explained in the [Terminology](service-connectors-guide.md#terminology) section: you can register a Service Connector that grants access to multiple types of resources, to multiple instances of the same Resource Type, or to a single resource. Service Connectors created from basic Service Connector Types like Kubernetes and Docker are single-resource by default, while Service Connectors used to connect to managed cloud resources like AWS and GCP can take all three forms.
Example of registering Service Connectors with different scopes The following example shows registering three different Service Connectors configured from the same AWS Service Connector Type using three different scopes but with the same credentials: * a multi-type AWS Service Connector that allows access to every possible resource accessible with the configured credentials * a multi-instance AWS Service Connector that allows access to multiple S3 buckets * a single-instance AWS Service Connector that only permits access to one S3 bucket ```sh zenml service-connector register aws-multi-type --type aws --auto-configure ``` {% code title="Example Command Output" %} ``` ⠋ Registering service connector 'aws-multi-type'... Successfully registered service connector `aws-multi-type` with access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┃ │ s3://zenml-public-datasets ┃ ┃ │ s3://zenml-public-swagger-spec ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector register aws-s3-multi-instance --type aws --auto-configure --resource-type s3-bucket ``` {% code title="Example Command Output" %} ``` ⠸ Registering service connector 'aws-s3-multi-instance'... Successfully registered service connector `aws-s3-multi-instance` with access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼───────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┃ │ s3://zenml-public-datasets ┃ ┃ │ s3://zenml-public-swagger-spec ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector register aws-s3-zenfiles --type aws --auto-configure --resource-type s3-bucket --resource-id s3://zenfiles ``` {% code title="Example Command Output" %} ``` ⠼ Registering service connector 'aws-s3-zenfiles'... Successfully registered service connector `aws-s3-zenfiles` with access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
The following might help understand the difference between scopes: * the difference between a multi-instance and a multi-type Service Connector is that the Resource Type scope is locked to a particular value during configuration for the multi-instance Service Connector * similarly, the difference between a multi-instance and a multi-type Service Connector is that the Resource Name (Resource ID) scope is locked to a particular value during configuration for the single-instance Service Connector ### Service Connector Verification When registering Service Connectors, the authentication configuration and credentials are automatically verified to ensure that they can indeed be used to gain access to the target resources: * for multi-type Service Connectors, this verification means checking that the configured credentials can be used to authenticate successfully to the remote service, as well as listing all resources that the credentials have permission to access for each Resource Type supported by the Service Connector Type. * for multi-instance Service Connectors, this verification step means listing all resources that the credentials have permission to access in addition to validating that the credentials can be used to authenticate to the target service or platform. * for single-instance Service Connectors, the verification step simply checks that the configured credentials have permission to access the target resource. The verification can also be performed later on an already registered Service Connector. Furthermore, for multi-type and multi-instance Service Connectors, the verification operation can be scoped to a Resource Type and a Resource Name.
Example of on-demand Service Connector verification The following shows how a multi-type, a multi-instance and a single-instance Service Connector can be verified with multiple scopes after registration. First, listing the Service Connectors will clarify which scopes they are configured with: ```sh zenml service-connector list ``` {% code title="Example Command Output" %} ``` ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┓ ┃ ACTIVE │ NAME │ ID │ TYPE │ RESOURCE TYPES │ RESOURCE NAME │ SHARED │ OWNER │ EXPIRES IN │ LABELS ┃ ┠────────┼───────────────────────┼──────────────────────────────────────┼────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ aws-multi-type │ 373a73c2-8295-45d4-a768-45f5a0f744ea │ 🔶 aws │ 🔶 aws-generic │ │ ➖ │ default │ │ ┃ ┃ │ │ │ │ 📦 s3-bucket │ │ │ │ │ ┃ ┃ │ │ │ │ 🌀 kubernetes-cluster │ │ │ │ │ ┃ ┃ │ │ │ │ 🐳 docker-registry │ │ │ │ │ ┃ ┠────────┼───────────────────────┼──────────────────────────────────────┼────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ aws-s3-multi-instance │ fa9325ab-ce01-4404-aec3-61a3af395d48 │ 🔶 aws │ 📦 s3-bucket │ │ ➖ │ default │ │ ┃ ┠────────┼───────────────────────┼──────────────────────────────────────┼────────┼───────────────────────┼───────────────┼────────┼─────────┼────────────┼────────┨ ┃ │ aws-s3-zenfiles │ 19edc05b-92db-49de-bc84-aa9b3fb8261a │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles │ ➖ │ default │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┛ ``` {% endcode %} Verifying the multi-type Service Connector displays all resources that can be accessed through the Service Connector. This is like asking "are these credentials valid? can they be used to authenticate to AWS ? and if so, what resources can they access?": ```sh zenml service-connector verify aws-multi-type ``` {% code title="Example Command Output" %} ``` Service connector 'aws-multi-type' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🔶 aws-generic │ us-east-1 ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠───────────────────────┼──────────────────────────────────────────────┨ ┃ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} You can scope the verification down to a particular Resource Type or all the way down to a Resource Name. This is the equivalent of asking "are these credentials valid and which S3 buckets are they authorized to access ?" and "can these credentials be used to access this particular Kubernetes cluster in AWS ?": ```sh zenml service-connector verify aws-multi-type --resource-type s3-bucket ``` {% code title="Example Command Output" %} ``` Service connector 'aws-multi-type' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼───────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector verify aws-multi-type --resource-type kubernetes-cluster --resource-id zenhacks-cluster ``` {% code title="Example Command Output" %} ``` Service connector 'aws-multi-type' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────────────┼──────────────────┨ ┃ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} Verifying the multi-instance Service Connector displays all the resources that it can access. We can also scope the verification to a single resource: ```sh zenml service-connector verify aws-s3-multi-instance ``` {% code title="Example Command Output" %} ``` Service connector 'aws-s3-multi-instance' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼───────────────────────────────────────┨ ┃ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ s3://zenfiles ┃ ┃ │ s3://zenml-demos ┃ ┃ │ s3://zenml-generative-chat ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector verify aws-s3-multi-instance --resource-id s3://zenml-demos ``` {% code title="Example Command Output" %} ``` Service connector 'aws-s3-multi-instance' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼──────────────────┨ ┃ 📦 s3-bucket │ s3://zenml-demos ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} Finally, verifying the single-instance Service Connector is straight-forward and requires no further explanation: ```sh zenml service-connector verify aws-s3-zenfiles ``` {% code title="Example Command Output" %} ``` Service connector 'aws-s3-zenfiles' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠───────────────┼────────────────┨ ┃ 📦 s3-bucket │ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
## Configure local clients Yet another neat feature built into some Service Container Types that is the opposite of [Service Connector auto-configuration](service-connectors-guide.md#auto-configuration) is the ability to configure local CLI and SDK utilities installed on your host, like the Docker or Kubernetes CLI (`kubectl`) with credentials issued by a compatible Service Connector. You may need to exercise this feature to get direct CLI access to a remote service in order to manually manage some configurations or resources, to debug some workloads or to simply verify that the Service Connector credentials are actually working. {% hint style="warning" %} When configuring local CLI utilities with credentials extracted from Service Connectors, keep in mind that most Service Connectors, particularly those used with cloud platforms, usually exercise the security best practice of issuing _temporary credentials such as API tokens._ The implication is that your local CLI may only be allowed access to the remote service for a short time before those credentials expire, then you need to fetch another set of credentials from the Service Connector. {% endhint %}
Examples of local CLI configuration The following examples show how the local Kubernetes `kubectl` CLI can be configured with credentials issued by a Service Connector and then used to access a Kubernetes cluster directly: ```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 ┃ ┠──────────────────────────────────────┼──────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────┨ ┃ 9d953320-3560-4a78-817c-926a3898064d │ gcp-user-multi │ 🔵 gcp │ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┠──────────────────────────────────────┼──────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────┨ ┃ 4a550c82-aa64-4a48-9c7f-d5e127d77a44 │ aws-multi-type │ 🔶 aws │ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector login gcp-user-multi --resource-type kubernetes-cluster --resource-id zenml-test-cluster ``` {% code title="Example Command Output" %} ``` $ zenml service-connector login gcp-user-multi --resource-type kubernetes-cluster --resource-id zenml-test-cluster ⠇ Attempting to configure local client using service connector 'gcp-user-multi'... Updated local kubeconfig with the cluster details. The current kubectl context was set to 'gke_zenml-core_zenml-test-cluster'. The 'gcp-user-multi' Kubernetes Service Connector connector was used to successfully configure the local Kubernetes cluster client/SDK. # Verify that the local kubectl client is now configured to access the remote Kubernetes cluster $ kubectl cluster-info Kubernetes control plane is running at https://35.185.95.223 GLBCDefaultBackend is running at https://35.185.95.223/api/v1/namespaces/kube-system/services/default-http-backend:http/proxy KubeDNS is running at https://35.185.95.223/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy Metrics-server is running at https://35.185.95.223/api/v1/namespaces/kube-system/services/https:metrics-server:/proxy ``` {% endcode %} ```sh zenml service-connector login aws-multi-type --resource-type kubernetes-cluster --resource-id zenhacks-cluster ``` {% code title="Example Command Output" %} ``` $ zenml service-connector login aws-multi-type --resource-type kubernetes-cluster --resource-id zenhacks-cluster ⠏ Attempting to configure local client using service connector 'aws-multi-type'... Updated local kubeconfig with the cluster details. The current kubectl context was set to 'arn:aws:eks:us-east-1:715803424590:cluster/zenhacks-cluster'. The 'aws-multi-type' Kubernetes Service Connector connector was used to successfully configure the local Kubernetes cluster client/SDK. # Verify that the local kubectl client is now configured to access the remote Kubernetes cluster $ kubectl cluster-info Kubernetes control plane is running at https://A5F8F4142FB12DDCDE9F21F6E9B07A18.gr7.us-east-1.eks.amazonaws.com CoreDNS is running at https://A5F8F4142FB12DDCDE9F21F6E9B07A18.gr7.us-east-1.eks.amazonaws.com/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy ``` {% endcode %} The same is possible with the local Docker client: ```sh zenml service-connector verify aws-session-token --resource-type docker-registry ``` {% code title="Example Command Output" %} ``` Service connector 'aws-session-token' is correctly configured with valid credentials and has access to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼───────────────────┼────────────────┼────────────────────┼──────────────────────────────────────────────┨ ┃ 3ae3e595-5cbc-446e-be64-e54e854e0e3f │ aws-session-token │ 🔶 aws │ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ```sh zenml service-connector login aws-session-token --resource-type docker-registry ``` {% code title="Example Command Output" %} ``` $zenml service-connector login aws-session-token --resource-type docker-registry ⠏ Attempting to configure local client using service connector 'aws-session-token'... 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-session-token' Docker Service Connector connector was used to successfully configure the local Docker/OCI container registry client/SDK. # Verify that the local Docker client is now configured to access the remote Docker container registry $ docker pull 715803424590.dkr.ecr.us-east-1.amazonaws.com/zenml-server Using default tag: latest latest: Pulling from zenml-server e9995326b091: Pull complete f3d7f077cdde: Pull complete 0db71afa16f3: Pull complete 6f0b5905c60c: Pull complete 9d2154d50fd1: Pull complete d072bba1f611: Pull complete 20e776588361: Pull complete 3ce69736a885: Pull complete c9c0554c8e6a: Pull complete bacdcd847a66: Pull complete 482033770844: Pull complete Digest: sha256:bf2cc3895e70dfa1ee1cd90bbfa599fa4cd8df837e27184bac1ce1cc239ecd3f Status: Downloaded newer image for 715803424590.dkr.ecr.us-east-1.amazonaws.com/zenml-server:latest 715803424590.dkr.ecr.us-east-1.amazonaws.com/zenml-server:latest ``` {% endcode %}
## Discover available resources One of the questions that you may have as a ZenML user looking to register and connect a Stack Component to an external resource is "what resources do I even have access to ?". Sure, you can browse through all the registered Service connectors and manually verify each one to find a particular resource that you are looking for, but this is counterproductive. A better way is to ask ZenML directly questions such as: * what are the Kubernetes clusters that I can get access to through Service Connectors? * can I access this particular S3 bucket through one of the Service Connectors? Which one? The `zenml service-connector list-resources` CLI command can be used exactly for this purpose.
Resource discovery examples It is possible to show globally all the various resources that can be accessed through all available Service Connectors, and all Service Connectors that are in an error state. This operation is expensive and may take some time to complete, depending on the number of Service Connectors involved. The output also includes any errors that may have occurred during the discovery process: ```sh zenml service-connector list-resources ``` {% code title="Example Command Output" %} ``` Fetching all service connector resources can take a long time, depending on the number of connectors that you have configured. Consider using the '--connector-type', '--resource-type' and '--resource-id' options to narrow down the list of resources to fetch. The following resources can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 099fb152-cfb7-4af5-86a7-7b77c0961b21 │ gcp-multi │ 🔵 gcp │ 🔵 gcp-generic │ zenml-core ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ │ │ │ 📦 gcs-bucket │ gs://annotation-gcp-store ┃ ┃ │ │ │ │ gs://zenml-bucket-sl ┃ ┃ │ │ │ │ gs://zenml-core.appspot.com ┃ ┃ │ │ │ │ gs://zenml-core_cloudbuild ┃ ┃ │ │ │ │ gs://zenml-datasets ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ │ │ │ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ │ │ │ 🐳 docker-registry │ gcr.io/zenml-core ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 373a73c2-8295-45d4-a768-45f5a0f744ea │ aws-multi-type │ 🔶 aws │ 🔶 aws-generic │ us-east-1 ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ │ │ │ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ │ │ │ s3://zenfiles ┃ ┃ │ │ │ │ s3://zenml-demos ┃ ┃ │ │ │ │ s3://zenml-generative-chat ┃ ┃ │ │ │ │ s3://zenml-public-datasets ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ │ │ │ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ │ │ │ 🐳 docker-registry │ 715803424590.dkr.ecr.us-east-1.amazonaws.com ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ fa9325ab-ce01-4404-aec3-61a3af395d48 │ aws-s3-multi-instance │ 🔶 aws │ 📦 s3-bucket │ s3://aws-ia-mwaa-715803424590 ┃ ┃ │ │ │ │ s3://zenfiles ┃ ┃ │ │ │ │ s3://zenml-demos ┃ ┃ │ │ │ │ s3://zenml-generative-chat ┃ ┃ │ │ │ │ s3://zenml-public-datasets ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 19edc05b-92db-49de-bc84-aa9b3fb8261a │ aws-s3-zenfiles │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ c732c768-3992-4cbd-8738-d02cd7b6b340 │ kubernetes-auto │ 🌀 kubernetes │ 🌀 kubernetes-cluster │ 💥 error: connector 'kubernetes-auto' authorization failure: failed to verify Kubernetes cluster ┃ ┃ │ │ │ │ access: (401) ┃ ┃ │ │ │ │ Reason: Unauthorized ┃ ┃ │ │ │ │ HTTP response headers: HTTPHeaderDict({'Audit-Id': '20c96e65-3e3e-4e08-bae3-bcb72c527fbf', ┃ ┃ │ │ │ │ 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'Date': 'Fri, 09 Jun 2023 ┃ ┃ │ │ │ │ 18:52:56 GMT', 'Content-Length': '129'}) ┃ ┃ │ │ │ │ HTTP response body: ┃ ┃ │ │ │ │ {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":" ┃ ┃ │ │ │ │ Unauthorized","code":401} ┃ ┃ │ │ │ │ ┃ ┃ │ │ │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} More interesting is to scope the search to a particular Resource Type. This yields fewer, more accurate results, especially if you have many multi-type Service Connectors configured: ```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 ┃ ┠──────────────────────────────────────┼─────────────────┼────────────────┼───────────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 099fb152-cfb7-4af5-86a7-7b77c0961b21 │ gcp-multi │ 🔵 gcp │ 🌀 kubernetes-cluster │ zenml-test-cluster ┃ ┠──────────────────────────────────────┼─────────────────┼────────────────┼───────────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ 373a73c2-8295-45d4-a768-45f5a0f744ea │ aws-multi-type │ 🔶 aws │ 🌀 kubernetes-cluster │ zenhacks-cluster ┃ ┠──────────────────────────────────────┼─────────────────┼────────────────┼───────────────────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────┨ ┃ c732c768-3992-4cbd-8738-d02cd7b6b340 │ kubernetes-auto │ 🌀 kubernetes │ 🌀 kubernetes-cluster │ 💥 error: connector 'kubernetes-auto' authorization failure: failed to verify Kubernetes cluster access: ┃ ┃ │ │ │ │ (401) ┃ ┃ │ │ │ │ Reason: Unauthorized ┃ ┃ │ │ │ │ HTTP response headers: HTTPHeaderDict({'Audit-Id': '72558f83-e050-4fe3-93e5-9f7e66988a4c', 'Cache-Control': ┃ ┃ │ │ │ │ 'no-cache, private', 'Content-Type': 'application/json', 'Date': 'Fri, 09 Jun 2023 18:59:02 GMT', ┃ ┃ │ │ │ │ 'Content-Length': '129'}) ┃ ┃ │ │ │ │ HTTP response body: ┃ ┃ │ │ │ │ {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauth ┃ ┃ │ │ │ │ orized","code":401} ┃ ┃ │ │ │ │ ┃ ┃ │ │ │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ``` {% endcode %} Finally, you can ask for a particular resource, if you know its Resource Name beforehand: ```sh zenml service-connector list-resources --resource-type s3-bucket --resource-id zenfiles ``` {% code title="Example Command Output" %} ``` The 's3-bucket' resource with name 'zenfiles' can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────┼────────────────┨ ┃ 373a73c2-8295-45d4-a768-45f5a0f744ea │ aws-multi-type │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────┼────────────────┨ ┃ fa9325ab-ce01-4404-aec3-61a3af395d48 │ aws-s3-multi-instance │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────┼────────────────┨ ┃ 19edc05b-92db-49de-bc84-aa9b3fb8261a │ aws-s3-zenfiles │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %}
## Connect Stack Components to resources Service Connectors and the resources and services that they can authenticate to and grant access to are only useful because they are a means of providing Stack Components a better and easier way of accessing external resources. If you are looking for a quick, assisted tour, we recommend using the interactive CLI mode to connect a Stack Component to a compatible Service Connector, especially if this is your first time doing it, e.g.: ``` zenml artifact-store connect -i zenml orchestrator connect -i zenml container-registry connect -i ``` To connect a Stack Component to an external resource or service, you first need to [register one or more Service Connectors](service-connectors-guide.md#register-service-connectors), or have someone else in your team with more infrastructure knowledge do it for you. If you already have that covered, you might want to ask ZenML "which resources/services am I even authorized to access with the available Service Connectors?". [The resource discovery feature](service-connectors-guide.md#end-to-end-examples) is designed exactly for this purpose. This last check is already included in the interactive ZenML CLI command used to connect a Stack Component to a remote resource. {% hint style="info" %} Not all Stack Components support being connected to an external resource or service via a Service Connector. Whether a Stack Component can use a Service Connector to connect to a remote resource or service or not is shown in the Stack Component flavor details: ``` $ zenml artifact-store flavor describe s3 Configuration class: S3ArtifactStoreConfig Configuration for the S3 Artifact Store. [...] This flavor supports connecting to external resources with a Service Connector. It requires a 's3-bucket' resource. You can get a list of all available connectors and the compatible resources that they can access by running: 'zenml service-connector list-resources --resource-type s3-bucket' If no compatible Service Connectors are yet registered, you can can register a new one by running: 'zenml service-connector register -i' ``` {% endhint %} For Stack Components that do support Service Connectors, their flavor indicates the Resource Type and, optionally, Service Connector Type compatible with the Stack Component. This can be used to figure out which resources are available and which Service Connectors can grant access to them. In some cases it is even possible to figure out the exact Resource Name based on the attributes already configured in the Stack Component, which is how ZenML can decide automatically which Resource Name to use in the interactive mode: ```sh zenml artifact-store register s3-zenfiles --flavor s3 --path=s3://zenfiles zenml service-connector list-resources --resource-type s3-bucket --resource-id s3://zenfiles zenml artifact-store connect s3-zenfiles --connector aws-multi-type ``` {% code title="Example Command Output" %} ``` $ zenml artifact-store register s3-zenfiles --flavor s3 --path=s3://zenfiles Running with active stack: 'default' (global) Successfully registered artifact_store `s3-zenfiles`. $ zenml service-connector list-resources --resource-type s3-bucket --resource-id zenfiles The 's3-bucket' resource with name 'zenfiles' can be accessed by service connectors that you have configured: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼──────────────────────┼────────────────┼───────────────┼────────────────┨ ┃ 4a550c82-aa64-4a48-9c7f-d5e127d77a44 │ aws-multi-type │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┠──────────────────────────────────────┼──────────────────────┼────────────────┼───────────────┼────────────────┨ ┃ 66c0922d-db84-4e2c-9044-c13ce1611613 │ aws-multi-instance │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┠──────────────────────────────────────┼──────────────────────┼────────────────┼───────────────┼────────────────┨ ┃ 65c82e59-cba0-4a01-b8f6-d75e8a1d0f55 │ aws-single-instance │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ $ zenml artifact-store connect s3-zenfiles --connector aws-multi-type Running with active stack: 'default' (global) Successfully connected artifact store `s3-zenfiles` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼────────────────┼────────────────┼───────────────┼────────────────┨ ┃ 4a550c82-aa64-4a48-9c7f-d5e127d77a44 │ aws-multi-type │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} The following is an example of connecting the same Stack Component to the remote resource using the interactive CLI mode: ```sh zenml artifact-store connect s3-zenfiles -i ``` {% code title="Example Command Output" %} ``` The following connectors have compatible resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────┼────────────────┨ ┃ 373a73c2-8295-45d4-a768-45f5a0f744ea │ aws-multi-type │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────┼────────────────┨ ┃ fa9325ab-ce01-4404-aec3-61a3af395d48 │ aws-s3-multi-instance │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┠──────────────────────────────────────┼───────────────────────┼────────────────┼───────────────┼────────────────┨ ┃ 19edc05b-92db-49de-bc84-aa9b3fb8261a │ aws-s3-zenfiles │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ Please enter the name or ID of the connector you want to use: aws-s3-zenfiles Successfully connected artifact store `s3-zenfiles` to the following resources: ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ CONNECTOR ID │ CONNECTOR NAME │ CONNECTOR TYPE │ RESOURCE TYPE │ RESOURCE NAMES ┃ ┠──────────────────────────────────────┼─────────────────┼────────────────┼───────────────┼────────────────┨ ┃ 19edc05b-92db-49de-bc84-aa9b3fb8261a │ aws-s3-zenfiles │ 🔶 aws │ 📦 s3-bucket │ s3://zenfiles ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ ``` {% endcode %} ## End-to-end examples To get an idea of what a complete end-to-end journey looks like, from registering Service Connector all the way to configuring Stacks and Stack Components and running pipelines that access remote resources through Service Connectors, take a look at the following full-fledged examples: * [the AWS Service Connector end-to-end examples](aws-service-connector.md) * [the GCP Service Connector end-to-end examples](gcp-service-connector.md) * [the Azure Service Connector end-to-end examples](azure-service-connector.md)
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/infrastructure-as-code/best-practices.md ================ --- description: Best practices for using IaC with ZenML --- # Architecting ML Infrastructure with ZenML and Terraform ## The Challenge You're a system architect tasked with setting up a scalable ML infrastructure that needs to: - Support multiple ML teams with different requirements - Work across multiple environments (dev, staging, prod) - Maintain security and compliance standards - Allow teams to iterate quickly without infrastructure bottlenecks ## The ZenML Approach ZenML introduces [stack components](../../../component-guide/README.md) as abstractions over infrastructure resources. Let's explore how to architect this effectively with Terraform using the official ZenML provider. ## Part 1: Foundation - Stack Component Architecture ### The Problem Different teams need different ML infrastructure configurations, but you want to maintain consistency and reusability. ### The Solution: Component-Based Architecture Start by breaking down your infrastructure into reusable modules that map to ZenML stack components: ```hcl # modules/zenml_stack_base/main.tf terraform { required_providers { zenml = { source = "zenml-io/zenml" } google = { source = "hashicorp/google" } } } resource "random_id" "suffix" { # This will generate a string of 12 characters, encoded as base64 which makes # it 8 characters long byte_length = 6 } # Create base infrastructure resources, including a shared object storage, # and container registry. This module should also create resources used to # authenticate with the cloud provider and authorize access to the resources # (e.g. user accounts, service accounts, workload identities, roles, # permissions etc.) module "base_infrastructure" { source = "./modules/base_infra" environment = var.environment project_id = var.project_id region = var.region # Generate consistent random naming across resources resource_prefix = "zenml-${var.environment}-${random_id.suffix.hex}" } # Create a flexible service connector for authentication resource "zenml_service_connector" "base_connector" { name = "${var.environment}-base-connector" type = "gcp" auth_method = "service-account" configuration = { project_id = var.project_id region = var.region service_account_json = module.base_infrastructure.service_account_key } labels = { environment = var.environment } } # Create base stack components resource "zenml_stack_component" "artifact_store" { name = "${var.environment}-artifact-store" type = "artifact_store" flavor = "gcp" configuration = { path = "gs://${module.base_infrastructure.artifact_store_bucket}/artifacts" } connector_id = zenml_service_connector.base_connector.id } resource "zenml_stack_component" "container_registry" { name = "${var.environment}-container-registry" type = "container_registry" flavor = "gcp" configuration = { uri = module.base_infrastructure.container_registry_uri } connector_id = zenml_service_connector.base_connector.id } resource "zenml_stack_component" "orchestrator" { name = "${var.environment}-orchestrator" type = "orchestrator" flavor = "vertex" configuration = { location = var.region workload_service_account = "${module.base_infrastructure.service_account_email}" } connector_id = zenml_service_connector.base_connector.id } # Create the base stack resource "zenml_stack" "base_stack" { name = "${var.environment}-base-stack" components = { artifact_store = zenml_stack_component.artifact_store.id container_registry = zenml_stack_component.container_registry.id orchestrator = zenml_stack_component.orchestrator.id } labels = { environment = var.environment type = "base" } } ``` Teams can extend this base stack: ```hcl # team_configs/training_stack.tf # Add training-specific components resource "zenml_stack_component" "training_orchestrator" { name = "${var.environment}-training-orchestrator" type = "orchestrator" flavor = "vertex" configuration = { location = var.region machine_type = "n1-standard-8" gpu_enabled = true synchronous = true } connector_id = zenml_service_connector.base_connector.id } # Create specialized training stack resource "zenml_stack" "training_stack" { name = "${var.environment}-training-stack" components = { artifact_store = zenml_stack_component.artifact_store.id container_registry = zenml_stack_component.container_registry.id orchestrator = zenml_stack_component.training_orchestrator.id } labels = { environment = var.environment type = "training" } } ``` ## Part 2: Environment Management and Authentication ### The Problem Different environments (dev, staging, prod) require: - Different authentication methods and security levels - Environment-specific resource configurations - Isolation between environments to prevent cross-environment impacts - Consistent management patterns while maintaining flexibility ### The Solution: Environment Configuration Pattern with Smart Authentication Create a flexible [service connector](../auth-management/README.md) setup that adapts to your environment. For example, in development, a service account might be the more flexible pattern, while in production we go through workload identity. Combine environment-specific configurations with appropriate authentication methods: ```hcl locals { # Define configurations per environment env_config = { dev = { # Resource configuration machine_type = "n1-standard-4" gpu_enabled = false # Authentication configuration auth_method = "service-account" auth_configuration = { service_account_json = file("dev-sa.json") } } prod = { # Resource configuration machine_type = "n1-standard-8" gpu_enabled = true # Authentication configuration auth_method = "external-account" auth_configuration = { external_account_json = file("prod-sa.json") } } } } # Create environment-specific connector resource "zenml_service_connector" "env_connector" { name = "${var.environment}-connector" type = "gcp" auth_method = local.env_config[var.environment].auth_method dynamic "configuration" { for_each = try(local.env_config[var.environment].auth_configuration, {}) content { key = configuration.key value = configuration.value } } } # Create environment-specific orchestrator resource "zenml_stack_component" "env_orchestrator" { name = "${var.environment}-orchestrator" type = "orchestrator" flavor = "vertex" configuration = { location = var.region machine_type = local.env_config[var.environment].machine_type gpu_enabled = local.env_config[var.environment].gpu_enabled } connector_id = zenml_service_connector.env_connector.id labels = { environment = var.environment } } ``` ## Part 3: Resource Sharing and Isolation ### The Problem Different ML projects often require strict isolation of data and security to prevent unauthorized access and ensure compliance with security policies. Ensuring that each project has its own isolated resources, such as artifact stores or orchestrators, is crucial to prevent data leakage and maintain the integrity of each project's environment. This focus on data and security isolation is essential for managing multiple ML projects securely and effectively. ### The Solution: Resource Scoping Pattern Implement resource sharing with project isolation: ```hcl locals { project_paths = { fraud_detection = "projects/fraud_detection/${var.environment}" recommendation = "projects/recommendation/${var.environment}" } } # Create shared artifact store components with project isolation resource "zenml_stack_component" "project_artifact_stores" { for_each = local.project_paths name = "${each.key}-artifact-store" type = "artifact_store" flavor = "gcp" configuration = { path = "gs://${var.shared_bucket}/${each.value}" } connector_id = zenml_service_connector.env_connector.id labels = { project = each.key environment = var.environment } } # The orchestrator is shared across all stacks resource "zenml_stack_component" "project_orchestrator" { name = "shared-orchestrator" type = "orchestrator" flavor = "vertex" configuration = { location = var.region project = var.project_id } connector_id = zenml_service_connector.env_connector.id labels = { environment = var.environment } } # Create project-specific stacks separated by artifact stores resource "zenml_stack" "project_stacks" { for_each = local.project_paths name = "${each.key}-stack" components = { artifact_store = zenml_stack_component.project_artifact_stores[each.key].id orchestrator = zenml_stack_component.project_orchestrator.id } labels = { project = each.key environment = var.environment } } ``` ## Part 4: Advanced Stack Management Practices 1. **Stack Component Versioning** ```hcl locals { stack_version = "1.2.0" common_labels = { version = local.stack_version managed_by = "terraform" environment = var.environment } } resource "zenml_stack" "versioned_stack" { name = "stack-v${local.stack_version}" labels = local.common_labels } ``` 2. **Service Connector Management** ```hcl # Create environment-specific connectors with clear purposes resource "zenml_service_connector" "env_connector" { name = "${var.environment}-${var.purpose}-connector" type = var.connector_type # Use workload identity for production auth_method = var.environment == "prod" ? "workload-identity" : "service-account" # Use a specific resource type and resource ID resource_type = var.resource_type resource_id = var.resource_id labels = merge(local.common_labels, { purpose = var.purpose }) } ``` 3. **Component Configuration Management** ```hcl # Define reusable configurations locals { base_configs = { orchestrator = { location = var.region project = var.project_id } artifact_store = { path_prefix = "gs://${var.bucket_name}" } } # Environment-specific overrides env_configs = { dev = { orchestrator = { machine_type = "n1-standard-4" } } prod = { orchestrator = { machine_type = "n1-standard-8" } } } } resource "zenml_stack_component" "configured_component" { name = "${var.environment}-${var.component_type}" type = var.component_type # Merge configurations configuration = merge( local.base_configs[var.component_type], try(local.env_configs[var.environment][var.component_type], {}) ) } ``` 4. **Stack Organization and Dependencies** ```hcl # Group related components with clear dependency chains module "ml_stack" { source = "./modules/ml_stack" depends_on = [ module.base_infrastructure, module.security ] components = { # Core components artifact_store = module.storage.artifact_store_id container_registry = module.container.registry_id # Optional components based on team needs orchestrator = var.needs_orchestrator ? module.compute.orchestrator_id : null experiment_tracker = var.needs_tracking ? module.mlflow.tracker_id : null } labels = merge(local.common_labels, { stack_type = "ml-platform" }) } ``` 5. **State Management** ```hcl terraform { backend "gcs" { prefix = "terraform/state" } # Separate state files for infrastructure and ZenML workspace_prefix = "zenml-" } # Use data sources to reference infrastructure state data "terraform_remote_state" "infrastructure" { backend = "gcs" config = { bucket = var.state_bucket prefix = "terraform/infrastructure" } } ``` These practices help maintain a clean, scalable, and maintainable infrastructure codebase while following infrastructure-as-code best practices. Remember to: - Keep configurations DRY using locals and variables - Use consistent naming conventions across resources - Document all required configuration fields - Consider component dependencies when organizing stacks - Separate infrastructure and ZenML registration state - Use [Terraform workspaces](https://www.terraform.io/docs/language/state/workspaces.html) for different environments - Ensure that the ML operations team manages the registration state to maintain control over the ZenML stack components and their configurations. This helps in keeping the infrastructure and ML operations aligned and allows for better tracking and auditing of changes. ## Conclusion Building ML infrastructure with ZenML and Terraform enables you to create a flexible, maintainable, and secure environment for ML teams. The official ZenML provider simplifies the process while maintaining clean infrastructure patterns. ================ File: docs/book/how-to/infrastructure-deployment/infrastructure-as-code/README.md ================ --- icon: network-wired description: > Leverage Infrastructure as Code to manage your ZenML stacks and components. --- # Integrate with Infrastructure as Code [Infrastructure as Code (IaC)](https://aws.amazon.com/what-is/iac) is the practice of managing and provisioning infrastructure through code instead of through manual processes. In this section, we will show you how to integrate ZenML with popular IaC tools such as [Terraform](https://www.terraform.io/). ![Screenshot of ZenML stack on Terraform Registry](../../../.gitbook/assets/terraform_providers_screenshot.png) ================ File: docs/book/how-to/infrastructure-deployment/infrastructure-as-code/terraform-stack-management.md ================ --- description: Registering Existing Infrastructure with ZenML - A Guide for Terraform Users --- # Manage your stacks with Terraform Terraform is a powerful tool for managing infrastructure as code, and is by far the most popular IaC tool. Many companies already have existing Terraform setups, and it is often desirable to integrate ZenML with this setup. We already got a glimpse on how to [deploy a cloud stack with Terraform](../stack-deployment/deploy-a-cloud-stack-with-terraform.md) using existing Terraform modules that are maintained by the ZenML team. While this is a great solution for quickly getting started, it might not always be suitable for your use case. This guide is for advanced users who want to manage their own custom Terraform code but want to use ZenML to manage their stacks. For this, the [ZenML provider](https://registry.terraform.io/providers/zenml-io/zenml/latest) is a better choice. ## Understanding the Two-Phase Approach When working with ZenML stacks, there are two distinct phases: 1. **Infrastructure Deployment**: Creating cloud resources (typically handled by platform teams) 2. **ZenML Registration**: Registering these resources as ZenML stack components While our official modules ([`zenml-stack/aws`](https://registry.terraform.io/modules/zenml-io/zenml-stack/aws/latest), [`zenml-stack/gcp`](https://registry.terraform.io/modules/zenml-io/zenml-stack/gcp/latest), [`zenml-stack/azure`](https://registry.terraform.io/modules/zenml-io/zenml-stack/azure/latest)) handle both phases, you might already have infrastructure deployed. Let's explore how to register existing infrastructure with ZenML. ## Phase 1: Infrastructure Deployment You likely already have this handled in your existing Terraform configurations: ```hcl # Example of existing GCP infrastructure resource "google_storage_bucket" "ml_artifacts" { name = "company-ml-artifacts" location = "US" } resource "google_artifact_registry_repository" "ml_containers" { repository_id = "ml-containers" format = "DOCKER" } ``` ## Phase 2: ZenML Registration ### Setup the ZenML Provider First, configure the [ZenML provider](https://registry.terraform.io/providers/zenml-io/zenml/latest) to communicate with your ZenML server: ```hcl terraform { required_providers { zenml = { source = "zenml-io/zenml" } } } provider "zenml" { # Configuration options will be loaded from environment variables: # ZENML_SERVER_URL # ZENML_API_KEY } ``` To generate a API key, use the command: ```bash zenml service-account create ``` You can learn more about how to generate a `ZENML_API_KEY` via service accounts [here](../../../how-to/manage-zenml-server/connecting-to-zenml/connect-with-a-service-account.md). ### Create the service connectors The key to successful registration is proper authentication between the components. [Service connectors](../../../how-to/infrastructure-deployment/auth-management/README.md) are ZenML's way of managing this: ```hcl # First, create a service connector resource "zenml_service_connector" "gcp_connector" { name = "gcp-${var.environment}-connector" type = "gcp" auth_method = "service-account" configuration = { project_id = var.project_id service_account_json = file("service-account.json") } } # Create a stack component referencing the connector resource "zenml_stack_component" "artifact_store" { name = "existing-artifact-store" type = "artifact_store" flavor = "gcp" configuration = { path = "gs://${google_storage_bucket.ml_artifacts.name}" } connector_id = zenml_service_connector.gcp_connector.id } ``` ### Register the stack components Register different types of [components](../../../component-guide/README.md): ```hcl # Generic component registration pattern locals { component_configs = { artifact_store = { type = "artifact_store" flavor = "gcp" configuration = { path = "gs://${google_storage_bucket.ml_artifacts.name}" } } container_registry = { type = "container_registry" flavor = "gcp" configuration = { uri = "${var.region}-docker.pkg.dev/${var.project_id}/${google_artifact_registry_repository.ml_containers.repository_id}" } } orchestrator = { type = "orchestrator" flavor = "vertex" configuration = { project = var.project_id region = var.region } } } } # Register multiple components resource "zenml_stack_component" "components" { for_each = local.component_configs name = "existing-${each.key}" type = each.value.type flavor = each.value.flavor configuration = each.value.configuration connector_id = zenml_service_connector.env_connector.id } ``` ### Assemble the stack Finally, assemble the components into a stack: ```hcl resource "zenml_stack" "ml_stack" { name = "${var.environment}-ml-stack" components = { for k, v in zenml_stack_component.components : k => v.id } } ``` ## Practical Walkthrough: Registering Existing GCP Infrastructure Let's see a complete example of registering an existing GCP infrastructure stack with ZenML. ### Prerequisites - A GCS bucket for artifacts - An Artifact Registry repository - A service account for ML operations - Vertex AI enabled for orchestration ### Step 1: Variables Configuration ```hcl # variables.tf variable "zenml_server_url" { description = "URL of the ZenML server" type = string } variable "zenml_api_key" { description = "API key for ZenML server authentication" type = string sensitive = true } variable "project_id" { description = "GCP project ID" type = string } variable "region" { description = "GCP region" type = string default = "us-central1" } variable "environment" { description = "Environment name (e.g., dev, staging, prod)" type = string } variable "gcp_service_account_key" { description = "GCP service account key in JSON format" type = string sensitive = true } ``` ### Step 2: Main Configuration ```hcl # main.tf terraform { required_providers { zenml = { source = "zenml-io/zenml" } google = { source = "hashicorp/google" } } } # Configure providers provider "zenml" { server_url = var.zenml_server_url api_key = var.zenml_api_key } provider "google" { project = var.project_id region = var.region } # Create GCP resources if needed resource "google_storage_bucket" "artifacts" { name = "${var.project_id}-zenml-artifacts-${var.environment}" location = var.region } resource "google_artifact_registry_repository" "containers" { location = var.region repository_id = "zenml-containers-${var.environment}" format = "DOCKER" } # ZenML Service Connector for GCP resource "zenml_service_connector" "gcp" { name = "gcp-${var.environment}" type = "gcp" auth_method = "service-account" configuration = { project_id = var.project_id region = var.region service_account_json = var.gcp_service_account_key } labels = { environment = var.environment managed_by = "terraform" } } # Artifact Store Component resource "zenml_stack_component" "artifact_store" { name = "gcs-${var.environment}" type = "artifact_store" flavor = "gcp" configuration = { path = "gs://${google_storage_bucket.artifacts.name}/artifacts" } connector_id = zenml_service_connector.gcp.id labels = { environment = var.environment } } # Container Registry Component resource "zenml_stack_component" "container_registry" { name = "gcr-${var.environment}" type = "container_registry" flavor = "gcp" configuration = { uri = "${var.region}-docker.pkg.dev/${var.project_id}/${google_artifact_registry_repository.containers.repository_id}" } connector_id = zenml_service_connector.gcp.id labels = { environment = var.environment } } # Vertex AI Orchestrator resource "zenml_stack_component" "orchestrator" { name = "vertex-${var.environment}" type = "orchestrator" flavor = "vertex" configuration = { location = var.region synchronous = true } connector_id = zenml_service_connector.gcp.id labels = { environment = var.environment } } # Complete Stack resource "zenml_stack" "gcp_stack" { name = "gcp-${var.environment}" components = { artifact_store = zenml_stack_component.artifact_store.id container_registry = zenml_stack_component.container_registry.id orchestrator = zenml_stack_component.orchestrator.id } labels = { environment = var.environment managed_by = "terraform" } } ``` ### Step 3: Outputs Configuration ```hcl # outputs.tf output "stack_id" { description = "ID of the created ZenML stack" value = zenml_stack.gcp_stack.id } output "stack_name" { description = "Name of the created ZenML stack" value = zenml_stack.gcp_stack.name } output "artifact_store_path" { description = "GCS path for artifacts" value = "${google_storage_bucket.artifacts.name}/artifacts" } output "container_registry_uri" { description = "URI of the container registry" value = "${var.region}-docker.pkg.dev/${var.project_id}/${google_artifact_registry_repository.containers.repository_id}" } ``` ### Step 4: terraform.tfvars Configuration Create a `terraform.tfvars` file (remember to never commit this to version control): ```hcl zenml_server_url = "https://your-zenml-server.com" project_id = "your-gcp-project-id" region = "us-central1" environment = "dev" ``` Store sensitive variables in environment variables: ```bash export TF_VAR_zenml_api_key="your-zenml-api-key" export TF_VAR_gcp_service_account_key=$(cat path/to/service-account-key.json) ``` ### Usage Instructions 1. Install required providers and initializing Terraform: ```bash terraform init ``` 2. Install required ZenML integrations: ```bash zenml integration install gcp ``` 3. Review the planned changes: ```bash terraform plan ``` 4. Apply the configuration: ```bash terraform apply ``` 5. Set the newly created stack as active: ```bash zenml stack set $(terraform output -raw stack_name) ``` 6. Verify the configuration: ```bash zenml stack describe ``` This complete example demonstrates: - Setting up necessary GCP infrastructure - Creating a service connector with proper authentication - Registering stack components with the infrastructure - Creating a complete ZenML stack - Proper variable management and output configuration - Best practices for sensitive information handling The same pattern can be adapted for AWS and Azure infrastructure by adjusting the provider configurations and resource types accordingly. Remember to: - Use appropriate IAM roles and permissions - Follow your organization's security practices for handling credentials - Consider using Terraform workspaces for managing multiple environments - Regular backup of your Terraform state files - Version control your Terraform configurations (excluding sensitive files) To learn more about the ZenML terraform provider, visit the [ZenML provider](https://registry.terraform.io/providers/zenml-io/zenml/latest). ================ File: docs/book/how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md ================ --- description: Deploy a cloud stack using Terraform --- # Deploy a cloud stack with Terraform ZenML maintains a collection of [Terraform modules](https://registry.terraform.io/modules/zenml-io/zenml-stack) designed to streamline the provisioning of cloud resources and seamlessly integrate them with ZenML Stacks. These modules simplify the setup process, allowing users to quickly provision cloud resources as well as configure and authorize ZenML to utilize them for running pipelines and other AI/ML operations. By leveraging these Terraform modules, users can ensure a more efficient and scalable deployment of their machine learning infrastructure, ultimately enhancing their development and operational workflows. The modules' implementation can also be used as a reference for creating custom Terraform configurations tailored to specific cloud environments and requirements. {% hint style="info" %} Terraform requires you to manage your infrastructure as code yourself. Among other things, this means that you will need to have Terraform installed on your machine and you will need to manually manage the state of your infrastructure. If you prefer a more automated approach, you can use [the 1-click stack deployment feature](deploy-a-cloud-stack.md) to deploy a cloud stack with ZenML with minimal knowledge of Terraform or cloud infrastructure for that matter. If you have the required infrastructure pieces already deployed on your cloud, you can also use [the stack wizard to seamlessly register your stack](../../infrastructure-deployment/stack-deployment/register-a-cloud-stack.md). {% endhint %} ## Pre-requisites To use this feature, you need a deployed ZenML server instance that is reachable from the cloud provider where you wish to have the stack provisioned (this can't be a local server started via `zenml login --local`). If you do not already have one set up, you can fast-track to trying out a ZenML Pro server by simply running `zenml login --pro` or [register for a free ZenML Pro account](https://cloud.zenml.io/signup). If you prefer to host your own, you can learn about self-hosting a ZenML server [here](../../../getting-started/deploying-zenml/README.md). Once you are connected to your deployed ZenML server, you need to create a service account and an API key for it. You will use the API key to give the Terraform module programmatic access to your ZenML server. You can find more about service accounts and API keys [here](../../../how-to/manage-zenml-server/connecting-to-zenml/connect-with-a-service-account.md). but the process is as simple as running the following CLI command while connected to your ZenML server: ```shell zenml service-account create ``` Example output: ```shell $ zenml service-account create terraform-account Created service account 'terraform-account'. Successfully created API key `default`. The API key value is: 'ZENKEY_...' Please store it safely as it will not be shown again. To configure a ZenML client to use this API key, run: zenml login https://842ed6a9-zenml.staging.cloudinfra.zenml.io --api-key and enter the following API key when prompted: ZENKEY_... ``` Finally, you will need the following on the machine where you will be running Terraform: * [Terraform](https://www.terraform.io/downloads.html) installed on your machine (version at least 1.9). * the ZenML Terraform stack modules assume you are already locally authenticated with your cloud provider through the provider's CLI or SDK tool and have permissions to create the resources that the modules will provision. This is different depending on the cloud provider you are using and is covered in the following sections. ## How to use the Terraform stack deployment modules If you are already knowledgeable with using Terraform and the cloud provider where you want to deploy the stack, this process will be straightforward. In a nutshell, you will need to: 1. set up the ZenML Terraform provider with your ZenML server URL and API key. It is recommended to use environment variables for this rather than hardcoding the values in your Terraform configuration file: ```shell export ZENML_SERVER_URL="https://your-zenml-server.com" export ZENML_API_KEY="" ``` 2. create a new Terraform configuration file (e.g., `main.tf`), preferably in a new directory, with the content that looks like this (`` can be `aws`, `gcp`, or `azure`): ```hcl terraform { required_providers { aws = { source = "hashicorp/aws" } zenml = { source = "zenml-io/zenml" } } } provider "zenml" { # server_url = # api_key = } module "zenml_stack" { source = "zenml-io/zenml-stack/" version = "x.y.z" # Optional inputs zenml_stack_name = "" orchestrator = "" # e.g., "local", "sagemaker", "vertex", "azureml", "skypilot" } output "zenml_stack_id" { value = module.zenml_stack.zenml_stack_id } output "zenml_stack_name" { value = module.zenml_stack.zenml_stack_name } ``` There might be a few additional required or optional inputs depending on the cloud provider you are using. You can find the full list of inputs for each module in the [Terraform Registry](https://registry.terraform.io/modules/zenml-io/zenml-stack) documentation for the relevant module or you can read on in the following sections. 3. Run the following commands in the directory where you have your Terraform configuration file: ```shell terraform init terraform apply ``` {% hint style="warning" %} The directory where you keep the Terraform configuration file and where you run the `terraform` commands is important. This is where Terraform will store the state of your infrastructure. Make sure you do not delete this directory or the state file it contains unless you are sure you no longer need to manage these resources with Terraform or after you have deprovisioned them up with `terraform destroy`. {% endhint %} 4. Terraform will prompt you to confirm the changes it will make to your cloud infrastructure. If you are happy with the changes, type `yes` and hit enter. 5. Terraform will then provision the resources you have specified in your configuration file. Once the process is complete, you will see a message indicating that the resources have been successfully created and printing out the ZenML stack ID and name: ```shell ... Apply complete! Resources: 15 added, 0 changed, 0 destroyed. Outputs: zenml_stack_id = "04c65b96-b435-4a39-8484-8cc18f89b991" zenml_stack_name = "terraform-gcp-588339e64d06" ``` At this point, a ZenML stack has also been created and registered with your ZenML server and you can start using it to run your pipelines: ```shell zenml integration install zenml stack set ``` You can find more details specific to the cloud provider of your choice in the next section: {% tabs %} {% tab title="AWS" %} The [original documentation for the ZenML AWS Terraform module](https://registry.terraform.io/modules/zenml-io/zenml-stack/aws/latest) contains extensive information about required permissions, inputs, outputs and provisioned resources. This is a summary of the key points from that documentation. ### Authentication To authenticate with AWS, you need to have [the AWS CLI](https://aws.amazon.com/cli/) installed on your machine and you need to have run `aws configure` to set up your credentials. ### Example Terraform Configuration Here is an example Terraform configuration file for deploying a ZenML stack on AWS: ```hcl terraform { required_providers { aws = { source = "hashicorp/aws" } zenml = { source = "zenml-io/zenml" } } } provider "zenml" { # server_url = # api_key = } provider "aws" { region = "eu-central-1" } module "zenml_stack" { source = "zenml-io/zenml-stack/aws" # Optional inputs orchestrator = "" # e.g., "local", "sagemaker", "skypilot" zenml_stack_name = "" } output "zenml_stack_id" { value = module.zenml_stack.zenml_stack_id } output "zenml_stack_name" { value = module.zenml_stack.zenml_stack_name } ``` ### Stack Components The Terraform module will create a ZenML stack configuration with the following components: 1. an S3 Artifact Store linked to a S3 bucket via an AWS Service Connector configured with IAM role credentials 2. an ECR Container Registry linked to a ECR repository via an AWS Service Connector configured with IAM role credentials 3. depending on the `orchestrator` input variable: * a local Orchestrator, if `orchestrator` is set to `local`. This can be used in combination with the SageMaker Step Operator to selectively run some steps locally and some on SageMaker. * if `orchestrator` is set to `sagemaker` (default): a SageMaker Orchestrator linked to the AWS account via an AWS Service Connector configured with IAM role credentials * if `orchestrator` is set to `skypilot`: a SkyPilot Orchestrator linked to the AWS account via an AWS Service Connector configured with IAM role credentials 4. an AWS CodeBuild Image Builder linked to the AWS account via an AWS Service Connector configured with IAM role credentials 5. a SageMaker Step Operator linked to the AWS account via an AWS Service Connector configured with IAM role credentials To use the ZenML stack, you will need to install the required integrations: * for the local or SageMaker orchestrator: ```shell zenml integration install aws s3 ``` * for the SkyPilot orchestrator: ```shell zenml integration install aws s3 skypilot_aws ``` {% endtab %} {% tab title="GCP" %} The [original documentation for the ZenML GCP Terraform module](https://registry.terraform.io/modules/zenml-io/zenml-stack/gcp/latest) contains extensive information about required permissions, inputs, outputs and provisioned resources. This is a summary of the key points from that documentation. ### Authentication To authenticate with GCP, you need to have [the `gcloud` CLI](https://cloud.google.com/sdk/gcloud) installed on your machine, and you need to have run `gcloud init` or `gcloud auth application-default login` to set up your credentials. ### Example Terraform Configuration Here is an example Terraform configuration file for deploying a ZenML stack on AWS: ```hcl terraform { required_providers { google = { source = "hashicorp/google" } zenml = { source = "zenml-io/zenml" } } } provider "zenml" { # server_url = # api_key = } provider "google" { region = "europe-west3" project = "my-project" } module "zenml_stack" { source = "zenml-io/zenml-stack/gcp" # Optional inputs orchestrator = "" # e.g., "local", "vertex", "skypilot" or "airflow" zenml_stack_name = "" } output "zenml_stack_id" { value = module.zenml_stack.zenml_stack_id } output "zenml_stack_name" { value = module.zenml_stack.zenml_stack_name } ``` ### Stack Components The Terraform module will create a ZenML stack configuration with the following components: 1. an GCP Artifact Store linked to a GCS bucket via a GCP Service Connector configured with the GCP service account credentials 2. an GCP Container Registry linked to a Google Artifact Registry via a GCP Service Connector configured with the GCP service account credentials 3. depending on the `orchestrator` input variable: * a local Orchestrator, if `orchestrator` is set to `local`. This can be used in combination with the Vertex AI Step Operator to selectively run some steps locally and some on Vertex AI. * if `orchestrator` is set to `vertex` (default): a Vertex AI Orchestrator linked to the GCP project via a GCP Service Connector configured with the GCP service account credentials * if `orchestrator` is set to `skypilot`: a SkyPilot Orchestrator linked to the GCP project via a GCP Service Connector configured with the GCP service account credentials * if `orchestrator` is set to `airflow`: an Airflow Orchestrator linked to the Cloud Composer environment 4. a Google Cloud Build Image Builder linked to your GCP project via a GCP Service Connector configured with the GCP service account credentials 5. a Vertex AI Step Operator linked to the GCP project via a GCP Service Connector configured with the GCP service account credentials To use the ZenML stack, you will need to install the required integrations: * for the local and Vertex AI orchestrators: ```shell zenml integration install gcp ``` * for the SkyPilot orchestrator: ```shell zenml integration install gcp skypilot_gcp ``` * for the Airflow orchestrator: ```shell zenml integration install gcp airflow ``` {% endtab %} {% tab title="Azure" %} The [original documentation for the ZenML Azure Terraform module](https://registry.terraform.io/modules/zenml-io/zenml-stack/azure/latest) contains extensive information about required permissions, inputs, outputs and provisioned resources. This is a summary of the key points from that documentation. ### Authentication To authenticate with Azure, you need to have [the Azure CLI](https://learn.microsoft.com/en-us/cli/azure/) installed on your machine and you need to have run `az login` to set up your credentials. ### Example Terraform Configuration Here is an example Terraform configuration file for deploying a ZenML stack on AWS: ```hcl terraform {{ required_providers {{ azurerm = {{ source = "hashicorp/azurerm" }} azuread = {{ source = "hashicorp/azuread" }} zenml = {{ source = "zenml-io/zenml" }} }} }} provider "zenml" { # server_url = # api_key = } provider "azurerm" {{ features {{ resource_group {{ prevent_deletion_if_contains_resources = false }} }} }} module "zenml_stack" { source = "zenml-io/zenml-stack/azure" # Optional inputs location = "" orchestrator = "" # e.g., "local", "skypilot_azure" zenml_stack_name = "" } output "zenml_stack_id" { value = module.zenml_stack.zenml_stack_id } output "zenml_stack_name" { value = module.zenml_stack.zenml_stack_name } ``` ### Stack Components The Terraform module will create a ZenML stack configuration with the following components: 1. an Azure Artifact Store linked to an Azure Storage Account and Blob Container via an Azure Service Connector configured with Azure Service Principal credentials 2. an ACR Container Registry linked to an Azure Container Registry via an Azure Service Connector configured with Azure Service Principal credentials 3. depending on the `orchestrator` input variable: * if `orchestrator` is set to `local`: a local Orchestrator. This can be used in combination with the AzureML Step Operator to selectively run some steps locally and some on AzureML. * if `orchestrator` is set to `skypilot` (default): an Azure SkyPilot Orchestrator linked to the Azure subscription via an Azure Service Connector configured with Azure Service Principal credentials * if `orchestrator` is set to `azureml`: an AzureML Orchestrator linked to an AzureML Workspace via an Azure Service Connector configured with Azure Service Principal credentials 4. an AzureML Step Operator linked to an AzureML Workspace via an Azure Service Connector configured with Azure Service Principal credentials To use the ZenML stack, you will need to install the required integrations: * for the local and AzureML orchestrators: ```shell zenml integration install azure ``` * for the SkyPilot orchestrator: ```shell zenml integration install azure skypilot_azure ``` {% endtab %} {% endtabs %} ## How to clean up the Terraform stack deployments Cleaning up the resources provisioned by Terraform is as simple as running the `terraform destroy` command in the directory where you have your Terraform configuration file. This will remove all the resources that were provisioned by the Terraform module and will also delete the ZenML stack that was registered with your ZenML server. ```shell terraform destroy ```
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md ================ --- description: Deploy a cloud stack from scratch with a single click --- # Deploy a cloud stack with a single click In ZenML, the [stack](../../../user-guide/production-guide/understand-stacks.md) is a fundamental concept that represents the configuration of your infrastructure. In a normal workflow, creating a stack requires you to first deploy the necessary pieces of infrastructure and then define them as stack components in ZenML with proper authentication. Especially in a remote setting, this process can be challenging and time-consuming, and it may create multi-faceted problems. This is why we implemented a feature, that allows you to **deploy the necessary pieces of infrastructure on your selected cloud provider and get you started on remote stack with a single click**. {% hint style="info" %} If you prefer to have more control over where and how resources are provisioned in your cloud, you can [use one of our Terraform modules](deploy-a-cloud-stack-with-terraform.md) to manage your infrastructure as code yourself. If you have the required infrastructure pieces already deployed on your cloud, you can also use [the stack wizard to seamlessly register your stack](../../infrastructure-deployment/stack-deployment/register-a-cloud-stack.md). {% endhint %} ## How to use the 1-click deployment tool? The first thing that you need in order to use this feature is a deployed instance of ZenML (not a local server via `zenml login --local`). If you do not already have it set up for you, feel free to learn how to do so [here](../../../getting-started/deploying-zenml/README.md). Once you are connected to your deployed ZenML instance, you can use the 1-click deployment tool either through the dashboard or the CLI: {% tabs %} {% tab title="Dashboard" %} In order to create a remote stack over the dashboard go to the stacks page on the dashboard and click "+ New Stack". ![The new stacks page](../../../.gitbook/assets/register_stack_button.png) Since we will be deploying it from scratch, select "New Infrastructure" on the next page: ![Options for registering a stack](../../../.gitbook/assets/register_stack_page.png) ![Choosing a cloud provider](../../../.gitbook/assets/deploy_stack_selection.png)
AWS If you choose `aws` as your provider, you will see a page where you will have to select a region and a name for your new stack: ![Configuring the new stack](../../../.gitbook/assets/deploy_stack_aws.png) Once the configuration is finished, you will see a deployment page: ![Deploying the new stack](../../../.gitbook/assets/deploy_stack_aws_2.png) Clicking on the "Deploy in AWS" button will redirect you to a Cloud Formation page on AWS Console. ![Cloudformation page](../../../.gitbook/assets/deploy_stack_aws_cloudformation_intro.png) You will have to log in to your AWS account, review and confirm the pre-filled configuration and create the stack. ![Finalizing the new stack](../../../.gitbook/assets/deploy_stack_aws_cloudformation.png)
GCP If you choose `gcp` as your provider, you will see a page where you will have to select a region and a name for your new stack: ![Deploy GCP Stack - Step 1](../../../.gitbook/assets/deploy_stack_gcp.png) ![Deploy GCP Stack - Step 1 Continued](../../../.gitbook/assets/deploy_stack_gcp_2.png) Once the configuration is finished, you will see a deployment page: ![Deploy GCP Stack - Step 2](../../../.gitbook/assets/deploy_stack_gcp_3.png) Make note of the configuration values provided to you in the ZenML dashboard. You will need these in the next step. Clicking on the "Deploy in GCP" button will redirect you to a Cloud Shell session on GCP. ![GCP Cloud Shell start page](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_start.png) {% hint style="warning" %} The Cloud Shell session will warn you that the ZenML GitHub repository is untrusted. We recommend that you review [the contents of the repository](https://github.com/zenml-io/zenml/tree/main/infra/gcp) and then check the `Trust repo` checkbox to proceed with the deployment, otherwise the Cloud Shell session will not be authenticated to access your GCP projects. You will also get a chance to review the scripts that will be executed in the Cloud Shell session before proceeding. {% endhint %} ![GCP Cloud Shell intro](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_intro.png) After the Cloud Shell session starts, you will be guided through the process of authenticating with GCP, configuring your deployment, and finally provisioning the resources for your new GCP stack using Deployment Manager. First, you will be asked to create or choose an existing GCP project with billing enabled and to configure your terminal with the selected project: ![GCP Cloud Shell tutorial step 1](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_step_1.png) Next, you will be asked to configure your deployment by pasting the configuration values that were provided to you earlier in the ZenML dashboard. You may need to switch back to the ZenML dashboard to copy these values if you did not do so earlier: ![GCP Cloud Shell tutorial step 2](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_step_2.png) ![Deploy GCP Stack pending](../../../.gitbook/assets/deploy_stack_pending.png) You can take this opportunity to review the script that will be executed at the next step. You will notice that this script starts by enabling some necessary GCP service APIs and configuring some basic permissions for the service accounts involved in the stack deployment, and then deploys the stack using a GCP Deployment Manager template. You can proceed with the deployment by running the script in your terminal: ![GCP Cloud Shell tutorial step 3](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_step_3.png) The script will deploy a GCP Deployment Manager template that provisions the necessary resources for your new GCP stack and automatically registers the stack with your ZenML server. You can monitor the progress of the deployment in your GCP console: ![GCP Deployment Manager progress](../../../.gitbook/assets/deploy_stack_gcp_dm_progress.png) Once the deployment is complete, you may close the Cloud Shell session and return to the ZenML dashboard to view the newly created stack: ![GCP Cloud Shell tutorial step 4](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_step_4.png) ![GCP Stack dashboard output](../../../.gitbook/assets/deploy_stack_gcp_dashboard_output.png)
Azure If you choose `azure` as your provider, you will see a page where you will have to select a location and a name for your new stack: ![Deploy Azure Stack - Step 1](../../../.gitbook/assets/deploy_stack_azure_location.png) You will also find a list of resources that will be deployed as part of the stack: ![Deploy Azure Stack - Step 1 Continued](../../../.gitbook/assets/deploy_stack_azure_resources.png) Once the configuration is finished, you will see a deployment page. Make note of the values in the `main.tf` file that is provided to you. ![Deploy Azure Stack - Step 2](../../../.gitbook/assets/deploy_stack_azure_deployment_page.png) Clicking on the "Deploy in Azure" button will redirect you to a Cloud Shell session on Azure. ![Azure Cloud Shell start page](../../../.gitbook/assets/deploy_stack_azure_cloud_shell.png) You should now paste the content of the `main.tf` file into a file int the Cloud Shell session and run the `terraform init --upgrade` and `terraform apply` commands. The `main.tf` file uses the `zenml-io/zenml-stack/azure` module hosted on the Terraform registry to deploy the necessary resources for your Azure stack and then automatically registers the stack with your ZenML server. You can check out the module documentation [here](https://registry.terraform.io/modules/zenml-io/zenml-stack/azure). ![Azure Cloud Shell Terraform Outputs](../../../.gitbook/assets/deploy_stack_azure_cloud_shell_terraform_outputs.png) Once the Terraform deployment is complete, you may close the Cloud Shell session and return to the ZenML Dashboard to view the newly created stack: ![Azure Stack Dashboard output](../../../.gitbook/assets/deploy_stack_azure_dashboard_output.png)
{% endtab %} {% tab title="CLI" %} In order to create a remote stack over the CLI, you can use the following command: ```shell zenml stack deploy -p {aws|gcp|azure} ``` ### AWS If you choose `aws` as your provider, the command will walk you through deploying a Cloud Formation stack on AWS. It will start by showing some information about the stack that will be created: ![CLI AWS stack deploy](../../../.gitbook/assets/deploy_stack_aws_cli.png) Upon confirmation, the command will redirect you to a Cloud Formation page on AWS Console where you will have to deploy the stack: ![Cloudformation page](../../../.gitbook/assets/deploy_stack_aws_cloudformation_intro.png) You will have to log in to your AWS account, have permission to deploy an AWS Cloud Formation stack, review and confirm the pre-filled configuration and create the stack. ![Finalizing the new stack](../../../.gitbook/assets/deploy_stack_aws_cloudformation.png) The Cloud Formation stack will provision the necessary resources for your new AWS stack and automatically register the stack with your ZenML server. You can monitor the progress of the stack in your AWS console: ![AWS Cloud Formation progress](../../../.gitbook/assets/deploy_stack_aws_cf_progress.png) Once the provisioning is complete, you may close the AWS Cloud Formation page and return to the ZenML CLI to view the newly created stack: ![AWS Stack CLI output](../../../.gitbook/assets/deploy_stack_aws_cli_output.png) ### GCP If you choose `gcp` as your provider, the command will walk you through deploying a Deployment Manager template on GCP. It will start by showing some information about the stack that will be created: ![CLI GCP stack deploy](../../../.gitbook/assets/deploy_stack_gcp_cli.png) Upon confirmation, the command will redirect you to a Cloud Shell session on GCP. ![GCP Cloud Shell start page](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_start.png) {% hint style="warning" %} The Cloud Shell session will warn you that the ZenML GitHub repository is untrusted. We recommend that you review [the contents of the repository](https://github.com/zenml-io/zenml/tree/main/infra/gcp) and then check the `Trust repo` checkbox to proceed with the deployment, otherwise the Cloud Shell session will not be authenticated to access your GCP projects. You will also get a chance to review the scripts that will be executed in the Cloud Shell session before proceeding. {% endhint %} ![GCP Cloud Shell intro](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_intro.png) After the Cloud Shell session starts, you will be guided through the process of authenticating with GCP, configuring your deployment, and finally provisioning the resources for your new GCP stack using Deployment Manager. First, you will be asked to create or choose an existing GCP project with billing enabled and to configure your terminal with the selected project: ![GCP Cloud Shell tutorial step 1](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_step_1.png) Next, you will be asked to configure your deployment by pasting the configuration values that were provided to you in the ZenML CLI. You may need to switch back to the ZenML CLI to copy these values if you did not do so earlier: ![GCP Cloud Shell tutorial step 2](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_step_2.png) You can take this opportunity to review the script that will be executed at the next step. You will notice that this script starts by enabling some necessary GCP service APIs and configuring some basic permissions for the service accounts involved in the stack deployment and then deploys the stack using a GCP Deployment Manager template. You can proceed with the deployment by running the script in your terminal: ![GCP Cloud Shell tutorial step 3](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_step_3.png) The script will deploy a GCP Deployment Manager template that provisions the necessary resources for your new GCP stack and automatically registers the stack with your ZenML server. You can monitor the progress of the deployment in your GCP console: ![GCP Deployment Manager progress](../../../.gitbook/assets/deploy_stack_gcp_dm_progress.png) Once the deployment is complete, you may close the Cloud Shell session and return to the ZenML CLI to view the newly created stack: ![GCP Cloud Shell tutorial step 4](../../../.gitbook/assets/deploy_stack_gcp_cloudshell_step_4.png) ![GCP Stack CLI output](../../../.gitbook/assets/deploy_stack_gcp_cli_output.png) ### Azure If you choose `azure` as your provider, the command will walk you through deploying [the ZenML Azure Stack Terraform module](https://registry.terraform.io/modules/zenml-io/zenml-stack/azure). It will start by showing some information about the stack that will be created: ![CLI Azure stack deploy](../../../.gitbook/assets/deploy_stack_azure_cli.png) Upon confirmation, the command will redirect you to a Cloud Shell session on Azure. ![Azure Cloud Shell page](../../../.gitbook/assets/deploy_stack_azure_cloudshell.png) After the Cloud Shell session starts, you will have to use Terraform to deploy the stack, as instructed by the CLI. First, you will have to open a file named `main.tf` in the Cloud Shell session using the editor of your choice (e.g. `vim`, `nano`) and paste in the Terraform configuration provided by the CLI. You may need to switch back to the ZenML CLI to copy these values if you did not do so earlier: ![Azure Cloud Shell Terraform Configuration File](../../../.gitbook/assets/deploy_stack_azure_cloudshell_create_file.png) The Terraform file is a simple configuration that uses [the ZenML Azure Stack Terraform module](https://registry.terraform.io/modules/zenml-io/zenml-stack/azure) to deploy the necessary resources for your Azure stack and then automatically register the stack with your ZenML server. You can read more about the module and its configuration options in the module's documentation. You can proceed with the deployment by running the `terraform init` and `terraform apply` Terraform commands in your terminal: ![Azure Cloud Shell Terraform Init](../../../.gitbook/assets/deploy_stack_azure_cloudshell_terraform_init.png) ![Azure Cloud Shell Terraform Apply](../../../.gitbook/assets/deploy_stack_azure_cloudshell_terraform_apply.png) Once the Terraform deployment is complete, you may close the Cloud Shell session and return to the ZenML CLI to view the newly created stack: ![Azure Cloud Shell Terraform Outputs](../../../.gitbook/assets/deploy_stack_azure_cloudshell_terraform_ouputs.png) ![Azure Stack CLI output](../../../.gitbook/assets/deploy_stack_azure_cli_output.png) {% endtab %} {% endtabs %} ## What will be deployed? Here is an overview of the infrastructure that the 1-click deployment will prepare for you based on your cloud provider: {% tabs %} {% tab title="AWS" %} ### Resources - An S3 bucket that will be used as a ZenML Artifact Store. - An ECR container registry that will be used as a ZenML Container Registry. - A CloudBuild project that will be used as a ZenML Image Builder. - Permissions to use SageMaker as a ZenML Orchestrator and Step Operator. - An IAM user and IAM role with the minimum necessary permissions to access the resources listed above. - An AWS access key used to give access to ZenML to connect to the above resources through a ZenML service connector. ### Permissions The configured IAM service account and AWS access key will grant ZenML the following AWS permissions in your AWS account: * S3 Bucket: * s3:ListBucket * s3:GetObject * s3:PutObject * s3:DeleteObject * s3:GetBucketVersioning * s3:ListBucketVersions * s3:DeleteObjectVersion * ECR Repository: * ecr:DescribeRepositories * ecr:ListRepositories * ecr:DescribeRegistry * ecr:BatchGetImage * ecr:DescribeImages * ecr:BatchCheckLayerAvailability * ecr:GetDownloadUrlForLayer * ecr:InitiateLayerUpload * ecr:UploadLayerPart * ecr:CompleteLayerUpload * ecr:PutImage * ecr:GetAuthorizationToken * CloudBuild (Client): * codebuild:CreateProject * codebuild:BatchGetBuilds * CloudBuild (Service): * s3:GetObject * s3:GetObjectVersion * logs:CreateLogGroup * logs:CreateLogStream * logs:PutLogEvents * ecr:BatchGetImage * ecr:DescribeImages * ecr:BatchCheckLayerAvailability * ecr:GetDownloadUrlForLayer * ecr:InitiateLayerUpload * ecr:UploadLayerPart * ecr:CompleteLayerUpload * ecr:PutImage * ecr:GetAuthorizationToken * SageMaker (Client): * sagemaker:CreatePipeline * sagemaker:StartPipelineExecution * sagemaker:DescribePipeline * sagemaker:DescribePipelineExecution * SageMaker (Jobs): * AmazonSageMakerFullAccess {% endtab %} {% tab title="GCP" %} ### Resources - A GCS bucket that will be used as a ZenML Artifact Store. - A GCP Artifact Registry that will be used as a ZenML Container Registry. - Permissions to use Vertex AI as a ZenML Orchestrator and Step Operator. - Permissions to use GCP Cloud Builder as a ZenML Image Builder. - A GCP Service Account with the minimum necessary permissions to access the resources listed above. - An GCP Service Account access key used to give access to ZenML to connect to the above resources through a ZenML service connector. ### Permissions The configured GCP service account and its access key will grant ZenML the following GCP permissions in your GCP project: * GCS Bucket: * roles/storage.objectUser * GCP Artifact Registry: * roles/artifactregistry.createOnPushWriter * Vertex AI (Client): * roles/aiplatform.user * Vertex AI (Jobs): * roles/aiplatform.serviceAgent * Cloud Build (Client): * roles/cloudbuild.builds.editor {% endtab %} {% tab title="Azure" %} ### Resources - An Azure Resource Group to contain all the resources required for the ZenML stack - An Azure Storage Account and Blob Storage Container that will be used as a ZenML Artifact Store. - An Azure Container Registry that will be used as a ZenML Container Registry. - An AzureML Workspace that will be used as a ZenML Orchestrator and ZenML Step Operator. A Key Vault and Application Insights instance will also be created in the same Resource Group and used to construct the AzureML Workspace. - An Azure Service Principal with the minimum necessary permissions to access the above resources. - An Azure Service Principal client secret used to give access to ZenML to connect to the above resources through a ZenML service connector. ### Permissions The configured Azure service principal and its client secret will grant ZenML the following permissions in your Azure subscription: * permissions granted for the created Storage Account: * Storage Blob Data Contributor * permissions granted for the created Container Registry: * AcrPull * AcrPush * Contributor * permissions granted for the created AzureML Workspace: * AzureML Compute Operator * AzureML Data Scientist {% endtab %} {% endtabs %} There you have it! With a single click, you just deployed a cloud stack and, you can start running your pipelines on a remote setting.
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/stack-deployment/export-stack-requirements.md ================ --- description: Export stack requirements --- You can get the `pip` requirements of your stack by running the `zenml stack export-requirements ` CLI command. To install those requirements, it's best to write them to a file and then install them like this: ```bash zenml stack export-requirements --output-file stack_requirements.txt pip install -r stack_requirements.txt ```
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md ================ --- description: How to write a custom stack component flavor --- # Implement a custom stack component When building a sophisticated MLOps Platform, you will often need to come up with custom-tailored solutions for your infrastructure or tooling. ZenML is built around the values of composability and reusability which is why the stack component flavors in ZenML are designed to be modular and straightforward to extend. This guide will help you understand what a flavor is, and how you can develop and use your own custom flavors in ZenML. ## Understanding component flavors In ZenML, a component type is a broad category that defines the functionality of a stack component. Each type can have multiple flavors, which are specific implementations of the component type. For instance, the type `artifact_store` can have flavors like `local`, `s3`, etc. Each flavor defines a unique implementation of functionality that an artifact store brings to a stack. ## Base Abstractions Before we get into the topic of creating custom stack component flavors, let us briefly discuss the three core abstractions related to stack components: the `StackComponent`, the `StackComponentConfig`, and the `Flavor`. ### Base Abstraction 1: `StackComponent` The `StackComponent` is the abstraction that defines the core functionality. As an example, check out the `BaseArtifactStore` definition below: The `BaseArtifactStore` inherits from `StackComponent` and establishes the public interface of all artifact stores. Any artifact store flavor needs to follow the standards set by this base class. ```python from zenml.stack import StackComponent class BaseArtifactStore(StackComponent): """Base class for all ZenML artifact stores.""" # --- public interface --- @abstractmethod def open(self, path, mode = "r"): """Open a file at the given path.""" @abstractmethod def exists(self, path): """Checks if a path exists.""" ... ``` As each component defines a different interface, make sure to check out the base class definition of the component type that you want to implement and also check out the [documentation on how to extend specific stack components](implement-a-custom-stack-component.md#extending-specific-stack-components). {% hint style="info" %} If you would like to automatically track some metadata about your custom stack component with each pipeline run, you can do so by defining some additional methods in your stack component implementation class as shown in the [Tracking Custom Stack Component Metadata](../..//model-management-metrics/track-metrics-metadata/fetch-metadata-within-steps.md) section. {% endhint %} See the full code of the base `StackComponent` class [here](https://github.com/zenml-io/zenml/blob/main/src/zenml/stack/stack\_component.py#L301). ### Base Abstraction 2: `StackComponentConfig` As the name suggests, the `StackComponentConfig` is used to configure a stack component instance. It is separated from the actual implementation on purpose. This way, ZenML can use this class to validate the configuration of a stack component during its registration/update, without having to import heavy (or even non-installed) dependencies. {% hint style="info" %} The `config` and `settings` of a stack component are two separate, yet related entities. The `config` is the static part of your flavor's configuration, defined when you register your flavor. The `settings` are the dynamic part of your flavor's configuration that can be overridden at runtime. You can read more about the differences [here](../../pipeline-development/use-configuration-files/runtime-configuration.md). {% endhint %} Let us now continue with the base artifact store example from above and take a look at the `BaseArtifactStoreConfig`: ```python from zenml.stack import StackComponentConfig class BaseArtifactStoreConfig(StackComponentConfig): """Config class for `BaseArtifactStore`.""" path: str SUPPORTED_SCHEMES: ClassVar[Set[str]] ... ``` Through the `BaseArtifactStoreConfig`, each artifact store will require users to define a `path` variable. Additionally, the base config requires all artifact store flavors to define a `SUPPORTED_SCHEMES` class variable that ZenML will use to check if the user-provided `path` is actually supported by the flavor. See the full code of the base `StackComponentConfig` class [here](https://github.com/zenml-io/zenml/blob/main/src/zenml/stack/stack\_component.py#L44). ### Base Abstraction 3: `Flavor` Finally, the `Flavor` abstraction is responsible for bringing the implementation of a `StackComponent` together with the corresponding `StackComponentConfig` definition and also defines the `name` and `type` of the flavor. As an example, check out the definition of the `local` artifact store flavor below: ```python from zenml.enums import StackComponentType from zenml.stack import Flavor class LocalArtifactStore(BaseArtifactStore): ... class LocalArtifactStoreConfig(BaseArtifactStoreConfig): ... class LocalArtifactStoreFlavor(Flavor): @property def name(self) -> str: """Returns the name of the flavor.""" return "local" @property def type(self) -> StackComponentType: """Returns the flavor type.""" return StackComponentType.ARTIFACT_STORE @property def config_class(self) -> Type[LocalArtifactStoreConfig]: """Config class of this flavor.""" return LocalArtifactStoreConfig @property def implementation_class(self) -> Type[LocalArtifactStore]: """Implementation class of this flavor.""" return LocalArtifactStore ``` See the full code of the base `Flavor` class definition [here](https://github.com/zenml-io/zenml/blob/main/src/zenml/stack/flavor.py#L29). ## Implementing a Custom Stack Component Flavor Let's recap what we just learned by reimplementing the `S3ArtifactStore` from the `aws` integration as a custom flavor. We can start with the configuration class: here we need to define the `SUPPORTED_SCHEMES` class variable introduced by the `BaseArtifactStore`. We also define several additional configuration values that users can use to configure how the artifact store will authenticate with AWS: ```python from zenml.artifact_stores import BaseArtifactStoreConfig from zenml.utils.secret_utils import SecretField class MyS3ArtifactStoreConfig(BaseArtifactStoreConfig): """Configuration for the S3 Artifact Store.""" SUPPORTED_SCHEMES: ClassVar[Set[str]] = {"s3://"} key: Optional[str] = SecretField(default=None) secret: Optional[str] = SecretField(default=None) token: Optional[str] = SecretField(default=None) client_kwargs: Optional[Dict[str, Any]] = None config_kwargs: Optional[Dict[str, Any]] = None s3_additional_kwargs: Optional[Dict[str, Any]] = None ``` {% hint style="info" %} You can pass sensitive configuration values as [secrets](../../../how-to/project-setup-and-management/interact-with-secrets.md) by defining them as type `SecretField` in the configuration class. {% endhint %} With the configuration defined, we can move on to the implementation class, which will use the S3 file system to implement the abstract methods of the `BaseArtifactStore`: ```python import s3fs from zenml.artifact_stores import BaseArtifactStore class MyS3ArtifactStore(BaseArtifactStore): """Custom artifact store implementation.""" _filesystem: Optional[s3fs.S3FileSystem] = None @property def filesystem(self) -> s3fs.S3FileSystem: """Get the underlying S3 file system.""" if self._filesystem: return self._filesystem self._filesystem = s3fs.S3FileSystem( key=self.config.key, secret=self.config.secret, token=self.config.token, client_kwargs=self.config.client_kwargs, config_kwargs=self.config.config_kwargs, s3_additional_kwargs=self.config.s3_additional_kwargs, ) return self._filesystem def open(self, path, mode: = "r"): """Custom logic goes here.""" return self.filesystem.open(path=path, mode=mode) def exists(self, path): """Custom logic goes here.""" return self.filesystem.exists(path=path) ``` {% hint style="info" %} The configuration values defined in the corresponding configuration class are always available in the implementation class under `self.config`. {% endhint %} Finally, let's define a custom flavor that brings these two classes together. Make sure that you give your flavor a globally unique name here. ```python from zenml.artifact_stores import BaseArtifactStoreFlavor class MyS3ArtifactStoreFlavor(BaseArtifactStoreFlavor): """Custom artifact store implementation.""" @property def name(self): """The name of the flavor.""" return 'my_s3_artifact_store' @property def implementation_class(self): """Implementation class for this flavor.""" from ... import MyS3ArtifactStore return MyS3ArtifactStore @property def config_class(self): """Configuration class for this flavor.""" from ... import MyS3ArtifactStoreConfig return MyS3ArtifactStoreConfig ``` {% hint style="info" %} For flavors that require additional dependencies, you should make sure to define your implementation, config, and flavor classes in separate Python files and to only import the implementation class inside the `implementation_class` property of the flavor class. Otherwise, ZenML will not be able to load and validate your flavor configuration without the dependencies installed. {% endhint %} ## Managing a Custom Stack Component Flavor Once you have defined your implementation, config, and flavor classes, you can register your new flavor through the ZenML CLI: ```shell zenml artifact-store flavor register ``` {% hint style="info" %} Make sure to point to the flavor class via dot notation! {% endhint %} For example, if your flavor class `MyS3ArtifactStoreFlavor` is defined in `flavors/my_flavor.py`, you'd register it by doing: ```shell zenml artifact-store flavor register flavors.my_flavor.MyS3ArtifactStoreFlavor ``` Afterwards, you should see the new custom artifact store flavor in the list of available artifact store flavors: ```shell zenml artifact-store flavor list ``` And that's it! You now have a custom stack component flavor that you can use in your stacks just like any other flavor you used before, e.g.: ```shell zenml artifact-store register \ --flavor=my_s3_artifact_store \ --path='some-path' \ ... zenml stack register \ --artifact-store \ ... ``` ## Tips and best practices * ZenML resolves the flavor classes by taking the path where you initialized ZenML (via `zenml init`) as the starting point of resolution. Therefore, you and your team should remember to execute `zenml init` in a consistent manner (usually at the root of the repository where the `.git` folder lives). If the `zenml init` command was not executed, the current working directory is used to find implementation classes, which could lead to unexpected behavior. * You can use the ZenML CLI to find which exact configuration values a specific flavor requires. Check out [this 3-minute video](https://www.youtube.com/watch?v=CQRVSKbBjtQ) for more information. * You can keep changing the `Config` and `Settings` of your flavor after registration. ZenML will pick up these "live" changes when running pipelines. * Note that changing the config in a breaking way requires an update of the component (not a flavor). E.g., adding a mandatory name to flavor X field will break a registered component of that flavor. This may lead to a completely broken state where one should delete the component and re-register it. * Always test your flavor thoroughly before using it in production. Make sure it works as expected and handles errors gracefully. * Keep your flavor code clean and well-documented. This will make it easier for others to use and contribute to your flavor. * Follow best practices for the language and libraries you're using. This will help ensure your flavor is efficient, reliable, and easy to maintain. * We recommend you develop new flavors by using existing flavors as a reference. A good starting point is the flavors defined in the [official ZenML integrations](https://github.com/zenml-io/zenml/tree/main/src/zenml/integrations). ## Extending Specific Stack Components If you would like to learn more about how to build a custom stack component flavor for a specific stack component type, check out the links below: | **Type of Stack Component** | **Description** | | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- | | [Orchestrator](../../../component-guide/orchestrators/custom.md) | Orchestrating the runs of your pipeline | | [Artifact Store](../../../component-guide/artifact-stores/custom.md) | Storage for the artifacts created by your pipelines | | [Container Registry](../../../component-guide/container-registries/custom.md) | Store for your containers | | [Step Operator](../../../component-guide/step-operators/custom.md) | Execution of individual steps in specialized runtime environments | | [Model Deployer](../../../component-guide/model-deployers/custom.md) | Services/platforms responsible for online model serving | | [Feature Store](../../../component-guide/feature-stores/custom.md) | Management of your data/features | | [Experiment Tracker](../../../component-guide/experiment-trackers/custom.md) | Tracking your ML experiments | | [Alerter](../../../component-guide/alerters/custom.md) | Sending alerts through specified channels | | [Annotator](../../../component-guide/annotators/custom.md) | Annotating and labeling data | | [Data Validator](../../../component-guide/data-validators/custom.md) | Validating and monitoring your data |
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/stack-deployment/README.md ================ --- icon: screwdriver-wrench description: > Stacks represent the infrastructure and tooling that defines where and how a pipeline executes. --- # Managing stacks & components ## What is a stack? The [stack](../../../user-guide/production-guide/understand-stacks.md) is a fundamental component of the ZenML framework. Put simply, a stack represents the configuration of the infrastructure and tooling that defines where and how a pipeline executes. A stack comprises different stack components, where each component is responsible for a specific task. For example, a stack might have a [container registry](../../../component-guide/container-registries/container-registries.md), a [Kubernetes cluster](../../../component-guide/orchestrators/kubernetes.md) as an [orchestrator](../../../component-guide/orchestrators/orchestrators.md), an [artifact store](../../../component-guide/artifact-stores/artifact-stores.md), an [experiment tracker](../../../component-guide/experiment-trackers/experiment-trackers.md) like MLflow and so on. ## Stacks as a way to organize your execution environment With ZenML, you can run your pipelines on more than one stacks with ease. This pattern helps you test your code across different environments effortlessly. This enables a case like this: a data scientist starts experimentation locally on their system and then once they are satisfied, move to a cloud environment on your staging cloud account to test more advanced features of your pipeline. Finally, when all looks good, they can mark the pipeline ready for production and have it run on a production-grade stack in your production cloud account. ![Stacks as a way to organize your execution environment](../../../.gitbook/assets/stack_envs.png) Having separate stacks for these environments helps: - avoid wrongfully deploying your staging pipeline to production - curb costs by running less powerful resources in staging and testing locally first - control access to environments by granting permissions for only certain stacks to certain users ## How to manage credentials for your stacks Most stack components require some form of credentials to interact with the underlying infrastructure. For example, a container registry needs to be authenticated to push and pull images, a Kubernetes cluster needs to be authenticated to deploy models as a web service, and so on. The preferred way to handle credentials in ZenML is to use [Service Connectors](../../infrastructure-deployment/auth-management/service-connectors-guide.md). Service connectors are a powerful feature of ZenML that allow you to abstract away credentials and sensitive information from your team. ![Service Connectors abstract away complexity and implement security best practices](../../../.gitbook/assets/ConnectorsDiagram.png) ### Recommended roles Ideally, you would want that only the people who deal with and have direct access to your cloud resources are the ones that are able to create Service Connectors. This is useful for a few reasons: - **Less chance of credentials leaking**: the more people that have access to your cloud resources, the higher the chance that some of them will be leaked. - **Instant revocation of compromised credentials**: folks who have direct access to your cloud resources can revoke the credentials instantly if they are compromised, making this a much more secure setup. - **Easier auditing**: you can have a much easier time auditing and tracking who did what if you have a clear separation between the people who can create Service Connectors (who have direct access to your cloud resources) and those who can only use them. ### Recommended workflow ![Recommended workflow for managing credentials](../../../.gitbook/assets/service_con_workflow.png) Here's an approach you can take that is a good balance between convenience and security: - Have a limited set of people that have permissions to create Service Connectors. These are ideally people that have access to your cloud accounts and know what credentials to use. - You can create one connector for your development or staging environment and let your data scientists use that to register their stack components. - When you are ready to go to production, you can create another connector with permissions for your production environment and create stacks that use it. This way you can ensure that your production resources are not accidentally used for development or staging. If you follow this approach, you can keep your data scientists free from the hassle of figuring out the best authentication mechanisms for the different cloud services, having to manage credentials locally, and keep your cloud accounts safe, while still giving them the freedom to run their experiments in the cloud. {% hint style="info" %} Please note that restricting permissions for users through roles is a ZenML Pro feature. You can read more about it [here](../../../getting-started/zenml-pro/roles.md). Sign up for a free trial here: https://cloud.zenml.io/. {% endhint %} ## How to deploy and manage stacks Deploying and managing a MLOps stack is tricky. * Each tool comes with a certain set of requirements. For example, a [Kubeflow installation](https://www.kubeflow.org/docs/started/installing-kubeflow/) will require you to have a Kubernetes cluster, and so would a **Seldon Core deployment**. * Figuring out the defaults for infra parameters is not easy. Even if you have identified the backing infra that you need for a stack component, setting up reasonable defaults for parameters like instance size, CPU, memory, etc., needs a lot of experimentation to figure out. * Many times, standard tool installations don't work out of the box. For example, to run a custom pipeline in [Vertex AI](https://cloud.google.com/vertex-ai), it is not enough to just run an imported pipeline. You might also need a custom service account that is configured to perform tasks like reading secrets from your secret store or talking to other GCP services that your pipeline might need. * Some tools need an additional layer of installations to enable a more secure, production-grade setup. For example, a standard **MLflow tracking server** deployment comes without an authentication frontend which might expose all of your tracking data to the world if deployed as-is. * All the components that you deploy must have the right permissions to be able to talk to each other. For example, your workloads running in a Kubernetes cluster might require access to the container registry or the code repository, and so on. * Cleaning up your resources after you're done with your experiments is super important yet very challenging. For example, if your Kubernetes cluster has made use of [Load Balancers](https://kubernetes.io/docs/concepts/services-networking/service/#loadbalancer), you might still have one lying around in your account even after deleting the cluster, costing you money and frustration. All of these points make taking your pipelines to production a more difficult task than it should be. We believe that the expertise in setting up these often-complex stacks shouldn't be a prerequisite to running your ML pipelines. This docs section consists of information that makes it easier to provision, configure, and extend stacks and components in ZenML.
Deploy a cloud stack with ZenML Deploy a cloud stack with ZenML ./deploy-a-cloud-stack.md
Register a cloud stack Register a cloud stack ./register-a-cloud-stack.md
Deploy a cloud stack with Terraform Deploy a cloud stack with Terraform ./deploy-a-cloud-stack-with-terraform.md
Export and install stack requirements Export and install stack requirements ./export-stack-requirements.md
Reference secrets in stack configuration Reference secrets in stack configuration ./reference-secrets-in-stack-configuration.md
Implement a custom stack component Creating your custom stack component solutions. ./implement-a-custom-stack-component.md
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/stack-deployment/reference-secrets-in-stack-configuration.md ================ --- description: Reference secrets in stack component attributes and settings --- # Reference secrets in stack configuration Some of the components in your stack require you to configure them with sensitive information like passwords or tokens, so they can connect to the underlying infrastructure. Secret references allow you to configure these components in a secure way by not specifying the value directly but instead referencing a secret by providing the secret name and key. Referencing a secret for the value of any string attribute of your stack components, simply specify the attribute using the following syntax: `{{.}}` For example: {% tabs %} {% tab title="CLI" %} ```shell # Register a secret called `mlflow_secret` with key-value pairs for the # username and password to authenticate with the MLflow tracking server # Using central secrets management zenml secret create mlflow_secret \ --username=admin \ --password=abc123 # Then 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}} \ ... ``` {% endtab %} {% endtabs %} When using secret references in your stack, ZenML will validate that all secrets and keys referenced in your stack components exist before running a pipeline. This helps us fail early so your pipeline doesn't fail after running for some time due to some missing secret. This validation by default needs to fetch and read every secret to make sure that both the secret and the specified key-value pair exist. This can take quite some time and might fail if you don't have permission to read secrets. You can use the environment variable `ZENML_SECRET_VALIDATION_LEVEL` to disable or control the degree to which ZenML validates your secrets: * Setting it to `NONE` disables any validation. * Setting it to `SECRET_EXISTS` only validates the existence of secrets. This might be useful if the machine you're running on only has permission to list secrets but not actually read their values. * Setting it to `SECRET_AND_KEY_EXISTS` (the default) validates both the secret existence as well as the existence of the exact key-value pair. ### Fetch secret values in a step If you are using [centralized secrets management](../../../how-to/project-setup-and-management/interact-with-secrets.md), you can access secrets directly from within your steps through the ZenML `Client` API. This allows you to use your secrets for querying APIs from within your step without hard-coding your access keys: ```python from zenml import step from zenml.client import Client @step def secret_loader() -> None: """Load the example secret from the server.""" # Fetch the secret from ZenML. secret = Client().get_secret( < SECRET_NAME >) # `secret.secret_values` will contain a dictionary with all key-value # pairs within your secret. authenticate_to_some_api( username=secret.secret_values["username"], password=secret.secret_values["password"], ) ... ``` ## See Also - [Interact with secrets](../../../how-to/project-setup-and-management/interact-with-secrets.md): Learn how to create, list, and delete secrets using the ZenML CLI and Python SDK.
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md ================ --- description: Seamlessly register a cloud stack by using existing infrastructure --- In ZenML, the [stack](../../../user-guide/production-guide/understand-stacks.md) is a fundamental concept that represents the configuration of your infrastructure. In a normal workflow, creating a stack requires you to first deploy the necessary pieces of infrastructure and then define them as stack components in ZenML with proper authentication. Especially in a remote setting, this process can be challenging and time-consuming, and it may create multi-faceted problems. This is why we implemented a feature called the stack wizard, that allows you to **browse through your existing infrastructure and use it to register a ZenML cloud stack**. {% hint style="info" %} If you do not have the required infrastructure pieces already deployed on your cloud, you can also use [the 1-click deployment tool to build your cloud stack](deploy-a-cloud-stack.md). Alternatively, if you prefer to have more control over where and how resources are provisioned in your cloud, you can [use one of our Terraform modules](deploy-a-cloud-stack-with-terraform.md) to manage your infrastructure as code yourself. {% endhint %} # How to use the Stack Wizard? The stack wizard is available to you by both our CLI and our dashboard. {% tabs %} {% tab title="Dashboard" %} If you are using the dashboard, the stack wizard is available through the stacks page. ![The new stacks page](../../../.gitbook/assets/stack-wizard-new-stack.png) Here you can click on "+ New Stack" and choose the option "Use existing Cloud". ![New stack options](../../../.gitbook/assets/stack-wizard-options.png) Next, you have to select the cloud provider that you want to work with. ![Stack Wizard Cloud Selection](../../../.gitbook/assets/stack-wizard-cloud-selection.png) Choose one of the possible authentication methods based on your provider and fill in the required fields. ![Wizard Example](../../../.gitbook/assets/stack-wizard-example.png)
AWS: Authentication methods If you select `aws` as your cloud provider, and you haven't selected a connector or declined auto-configuration, you will be prompted to select an authentication method for your cloud connector. {% code title="Available authentication methods for AWS" %} ``` Available authentication methods for AWS ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Choice ┃ Name ┃ Required ┃ ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ [0] │ AWS Secret Key │ aws_access_key_id (AWS Access │ │ │ │ Key ID) │ │ │ │ aws_secret_access_key (AWS │ │ │ │ Secret Access Key) │ │ │ │ region (AWS Region) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [1] │ AWS STS Token │ aws_access_key_id (AWS Access │ │ │ │ Key ID) │ │ │ │ aws_secret_access_key (AWS │ │ │ │ Secret Access Key) │ │ │ │ aws_session_token (AWS │ │ │ │ Session Token) │ │ │ │ region (AWS Region) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [2] │ AWS IAM Role │ aws_access_key_id (AWS Access │ │ │ │ Key ID) │ │ │ │ aws_secret_access_key (AWS │ │ │ │ Secret Access Key) │ │ │ │ region (AWS Region) │ │ │ │ role_arn (AWS IAM Role ARN) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [3] │ AWS Session Token │ aws_access_key_id (AWS Access │ │ │ │ Key ID) │ │ │ │ aws_secret_access_key (AWS │ │ │ │ Secret Access Key) │ │ │ │ region (AWS Region) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [4] │ AWS Federation Token │ aws_access_key_id (AWS Access │ │ │ │ Key ID) │ │ │ │ aws_secret_access_key (AWS │ │ │ │ Secret Access Key) │ │ │ │ region (AWS Region) │ │ │ │ │ └─────────┴────────────────────────────────┴────────────────────────────────┘ ``` {% endcode %}
GCP: Authentication methods If you select `gcp` as your cloud provider, and you haven't selected a connector or declined auto-configuration, you will be prompted to select an authentication method for your cloud connector. {% code title="Available authentication methods for GCP" %} ``` Available authentication methods for GCP ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Choice ┃ Name ┃ Required ┃ ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ [0] │ GCP User Account │ user_account_json (GCP User │ │ │ │ Account Credentials JSON │ │ │ │ optionally base64 encoded.) │ │ │ │ project_id (GCP Project ID │ │ │ │ where the target resource is │ │ │ │ located.) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [1] │ GCP Service Account │ service_account_json (GCP │ │ │ │ Service Account Key JSON │ │ │ │ optionally base64 encoded.) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [2] │ GCP External Account │ external_account_json (GCP │ │ │ │ External Account JSON │ │ │ │ optionally base64 encoded.) │ │ │ │ project_id (GCP Project ID │ │ │ │ where the target resource is │ │ │ │ located.) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [3] │ GCP Oauth 2.0 Token │ token (GCP OAuth 2.0 Token) │ │ │ │ project_id (GCP Project ID │ │ │ │ where the target resource is │ │ │ │ located.) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [4] │ GCP Service Account │ service_account_json (GCP │ │ │ Impersonation │ Service Account Key JSON │ │ │ │ optionally base64 encoded.) │ │ │ │ target_principal (GCP Service │ │ │ │ Account Email to impersonate) │ │ │ │ │ └─────────┴────────────────────────────────┴────────────────────────────────┘ ``` {% endcode %}
Azure: Authentication methods If you select `azure` as your cloud provider, and you haven't selected a connector or declined auto-configuration, you will be prompted to select an authentication method for your cloud connector. {% code title="Available authentication methods for Azure" %} ``` Available authentication methods for AZURE ┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Choice ┃ Name ┃ Required ┃ ┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ [0] │ Azure Service Principal │ client_secret (Service principal │ │ │ │ client secret) │ │ │ │ tenant_id (Azure Tenant ID) │ │ │ │ client_id (Azure Client ID) │ │ │ │ │ ├────────┼─────────────────────────┼────────────────────────────────────┤ │ [1] │ Azure Access Token │ token (Azure Access Token) │ │ │ │ │ └────────┴─────────────────────────┴────────────────────────────────────┘ ``` {% endcode %}
From this step forward, ZenML will show you different selections of resources that you can use from your existing infrastructure so that you can create the required stack components such as an artifact store, an orchestrator, and a container registry. {% endtab %} {% tab title="CLI" %} In order to register a remote stack over the CLI with the stack wizard, you can use the following command: ```shell zenml stack register -p {aws|gcp|azure} ``` To register the cloud stack, the first thing that the wizard needs is a [service connector](../../infrastructure-deployment/auth-management/service-connectors-guide.md). You can either use an existing connector by providing its ID or name `-sc ` (CLI-Only) or the wizard will create one for you. {% hint style="info" %} Similar to the service connector, if you use the CLI, you can also use existing stack components. However, this is only possible if these components are already configured with the same service connector that you provided through the parameter described above. {% endhint %} ### Define Service Connector As the very first step the configuration wizard will check if the selected cloud provider credentials can be acquired automatically from the local environment. If the credentials are found, you will be offered to use them or proceed to manual configuration. {% code title="Example prompt for AWS auto-configuration" %} ``` AWS cloud service connector has detected connection credentials in your environment. Would you like to use these credentials or create a new configuration by providing connection details? [y/n] (y): ``` {% endcode %} If you decline auto-configuration next you might be offered the list of already created service connectors available on the server: pick one of them and proceed or pick `0` to create a new one.
AWS: Authentication methods If you select `aws` as your cloud provider, and you haven't selected a connector or declined auto-configuration, you will be prompted to select an authentication method for your cloud connector. {% code title="Available authentication methods for AWS" %} ``` Available authentication methods for AWS ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Choice ┃ Name ┃ Required ┃ ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ [0] │ AWS Secret Key │ aws_access_key_id (AWS Access │ │ │ │ Key ID) │ │ │ │ aws_secret_access_key (AWS │ │ │ │ Secret Access Key) │ │ │ │ region (AWS Region) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [1] │ AWS STS Token │ aws_access_key_id (AWS Access │ │ │ │ Key ID) │ │ │ │ aws_secret_access_key (AWS │ │ │ │ Secret Access Key) │ │ │ │ aws_session_token (AWS │ │ │ │ Session Token) │ │ │ │ region (AWS Region) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [2] │ AWS IAM Role │ aws_access_key_id (AWS Access │ │ │ │ Key ID) │ │ │ │ aws_secret_access_key (AWS │ │ │ │ Secret Access Key) │ │ │ │ region (AWS Region) │ │ │ │ role_arn (AWS IAM Role ARN) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [3] │ AWS Session Token │ aws_access_key_id (AWS Access │ │ │ │ Key ID) │ │ │ │ aws_secret_access_key (AWS │ │ │ │ Secret Access Key) │ │ │ │ region (AWS Region) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [4] │ AWS Federation Token │ aws_access_key_id (AWS Access │ │ │ │ Key ID) │ │ │ │ aws_secret_access_key (AWS │ │ │ │ Secret Access Key) │ │ │ │ region (AWS Region) │ │ │ │ │ └─────────┴────────────────────────────────┴────────────────────────────────┘ ``` {% endcode %}
GCP: Authentication methods If you select `gcp` as your cloud provider, and you haven't selected a connector or declined auto-configuration, you will be prompted to select an authentication method for your cloud connector. {% code title="Available authentication methods for GCP" %} ``` Available authentication methods for GCP ┏━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Choice ┃ Name ┃ Required ┃ ┡━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ [0] │ GCP User Account │ user_account_json (GCP User │ │ │ │ Account Credentials JSON │ │ │ │ optionally base64 encoded.) │ │ │ │ project_id (GCP Project ID │ │ │ │ where the target resource is │ │ │ │ located.) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [1] │ GCP Service Account │ service_account_json (GCP │ │ │ │ Service Account Key JSON │ │ │ │ optionally base64 encoded.) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [2] │ GCP External Account │ external_account_json (GCP │ │ │ │ External Account JSON │ │ │ │ optionally base64 encoded.) │ │ │ │ project_id (GCP Project ID │ │ │ │ where the target resource is │ │ │ │ located.) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [3] │ GCP Oauth 2.0 Token │ token (GCP OAuth 2.0 Token) │ │ │ │ project_id (GCP Project ID │ │ │ │ where the target resource is │ │ │ │ located.) │ │ │ │ │ ├─────────┼────────────────────────────────┼────────────────────────────────┤ │ [4] │ GCP Service Account │ service_account_json (GCP │ │ │ Impersonation │ Service Account Key JSON │ │ │ │ optionally base64 encoded.) │ │ │ │ target_principal (GCP Service │ │ │ │ Account Email to impersonate) │ │ │ │ │ └─────────┴────────────────────────────────┴────────────────────────────────┘ ``` {% endcode %}
Azure: Authentication methods If you select `azure` as your cloud provider, and you haven't selected a connector or declined auto-configuration, you will be prompted to select an authentication method for your cloud connector. {% code title="Available authentication methods for Azure" %} ``` Available authentication methods for AZURE ┏━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Choice ┃ Name ┃ Required ┃ ┡━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ [0] │ Azure Service Principal │ client_secret (Service principal │ │ │ │ client secret) │ │ │ │ tenant_id (Azure Tenant ID) │ │ │ │ client_id (Azure Client ID) │ │ │ │ │ ├────────┼─────────────────────────┼────────────────────────────────────┤ │ [1] │ Azure Access Token │ token (Azure Access Token) │ │ │ │ │ └────────┴─────────────────────────┴────────────────────────────────────┘ ``` {% endcode %}
### Defining cloud components Next, you will define three major components of your target stack: - artifact store - orchestrator - container registry All three are crucial for a basic cloud stack. Extra components can be added later if they are needed. For each component, you will be asked: - if you would like to reuse one of the existing components connected via a defined service connector (if any) {% code title="Example Command Output for available orchestrator" %} ``` Available orchestrator ┏━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Choice ┃ Name ┃ ┡━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ [0] │ Create a new orchestrator │ ├──────────────────┼────────────────────────────────────────────────────┤ │ [1] │ existing_orchestrator_1 │ ├──────────────────┼────────────────────────────────────────────────────┤ │ [2] │ existing_orchestrator_2 │ └──────────────────┴────────────────────────────────────────────────────┘ ``` {% endcode %} - to create a new one from available to the service connector resources (if the existing not picked) {% code title="Example Command Output for Artifact Stores" %} ``` Available GCP storages ┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Choice ┃ Storage ┃ ┡━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ [0] │ gs://*************************** │ ├───────────────┼───────────────────────────────────────────────────────┤ │ [1] │ gs://*************************** │ └───────────────┴───────────────────────────────────────────────────────┘ ``` {% endcode %} Based on your selection, ZenML will create the stack component and ultimately register the stack for you. {% endtab %} {% endtabs %} There you have it! Through the wizard, you just registered a cloud stack and, you can start running your pipelines on a remote setting.
ZenML Scarf
================ File: docs/book/how-to/infrastructure-deployment/README.md ================ --- icon: cloud-word --- # Infrastructure and Deployment This section covers all aspects of infrastructure setup and deployment in ZenML. ================ File: docs/book/how-to/manage-zenml-server/connecting-to-zenml/connect-in-with-your-user-interactive.md ================ # Connect in with your User (interactive) You can authenticate your clients with the ZenML Server using the ZenML CLI and the web based login. This can be executed with the command: ```bash zenml login https://... ``` This command will start a series of steps to validate the device from where you are connecting that will happen in your browser. You can choose whether to mark your respective device as trusted or not. If you choose not to click `Trust this device`, a 24-hour token will be issued for authentication services. Choosing to trust the device will issue a 30-day token instead. To see all devices you've permitted, use the following command: ```bash zenml authorized-device list ``` Additionally, the following command allows you to more precisely inspect one of these devices: ```bash zenml authorized-device describe ``` For increased security, you can invalidate a token using the `zenml device lock` command followed by the device ID. This helps provide an extra layer of security and control over your devices. ``` zenml authorized-device lock ``` To keep things simple, we can summarize the steps: 1. Use the `zenml login ` command to start a device flow and connect to a zenml server. 2. Choose whether to trust the device when prompted. 3. Check permitted devices with `zenml devices list`. 4. Invalidate a token with `zenml device lock ...`. ### Important notice Using the ZenML CLI is a secure and comfortable way to interact with your ZenML tenants. It's important to always ensure that only trusted devices are used to maintain security and privacy. Don't forget to manage your device trust levels regularly for optimal security. Should you feel a device trust needs to be revoked, lock the device immediately. Every token issued is a potential gateway to access your data, secrets and infrastructure.
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/connecting-to-zenml/connect-with-a-service-account.md ================ # Connect with a Service Account Sometimes you may need to authenticate to a ZenML server from a non-interactive environment where the web login is not possible, like a CI/CD workload or a serverless function. In these cases, you can configure a service account and an API key and use the API key to authenticate to the ZenML server: ```bash zenml service-account create ``` This command creates a service account and an API key for it. The API key is displayed as part of the command output and cannot be retrieved later. You can then use the issued API key to connect your ZenML client to the server through one of the following methods: * using the CLI: ```bash # This command will prompt you to enter the API key zenml login https://... --api-key ``` * setting the `ZENML_STORE_URL` and `ZENML_STORE_API_KEY` environment variables when you set up your ZenML client for the first time. This method is particularly useful when you are using the ZenML client in an automated CI/CD workload environment like GitHub Actions or GitLab CI or in a containerized environment like Docker or Kubernetes: ```bash export ZENML_STORE_URL=https://... export ZENML_STORE_API_KEY= ``` {% hint style="info" %} You don't need to run `zenml login` after setting these two environment variables and can start interacting with your server right away. {% endhint %} To see all the service accounts you've created and their API keys, use the following commands: ```bash zenml service-account list zenml service-account api-key list ``` Additionally, the following command allows you to more precisely inspect one of these service accounts and an API key: ```bash zenml service-account describe zenml service-account api-key describe ``` API keys don't have an expiration date. For increased security, we recommend that you regularly rotate the API keys to prevent unauthorized access to your ZenML server. You can do this with the ZenML CLI: ```bash zenml service-account api-key rotate ``` Running this command will create a new API key and invalidate the old one. The new API key is displayed as part of the command output and cannot be retrieved later. You can then use the new API key to connect your ZenML client to the server just as described above. When rotating an API key, you can also configure a retention period for the old API key. This is useful if you need to keep the old API key for a while to ensure that all your workloads have been updated to use the new API key. You can do this with the `--retain` flag. For example, to rotate an API key and keep the old one for 60 minutes, you can run the following command: ```bash zenml service-account api-key rotate \ --retain 60 ``` For increased security, you can deactivate a service account or an API key using one of the following commands: ``` zenml service-account update --active false zenml service-account api-key update \ --active false ``` Deactivating a service account or an API key will prevent it from being used to authenticate and has immediate effect on all workloads that use it. To keep things simple, we can summarize the steps: 1. Use the `zenml service-account create` command to create a service account and an API key. 2. Use the `zenml login --api-key` command to connect your ZenML client to the server using the API key. 3. Check configured service accounts with `zenml service-account list`. 4. Check configured API keys with `zenml service-account api-key list`. 5. Regularly rotate API keys with `zenml service-account api-key rotate`. 6. Deactivate service accounts or API keys with `zenml service-account update` or `zenml service-account api-key update`. ### Important notice Every API key issued is a potential gateway to access your data, secrets and infrastructure. It's important to regularly rotate API keys and deactivate or delete service accounts and API keys that are no longer needed.
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/connecting-to-zenml/README.md ================ --- icon: globe-pointer description: Various means of connecting to ZenML. --- # Connect to a server Once [ZenML is deployed](../../../user-guide/production-guide/deploying-zenml.md), there are various ways to connect to it.
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/migration-guide/migration-guide.md ================ --- description: How to migrate your ZenML code to the newest version. --- # ♻ Migration guide Migrations are necessary for ZenML releases that include breaking changes, which are currently all releases that increment the minor version of the release, e.g., `0.X` -> `0.Y`. Furthermore, all releases that increment the first non-zero digit of the version contain major breaking changes or paradigm shifts that are explained in separate migration guides below. ## Release Type Examples * `0.40.2` to `0.40.3` contains _no breaking changes_ and requires no migration whatsoever, * `0.40.3` to `0.41.0` contains _minor breaking changes_ that need to be taken into account when upgrading ZenML, * `0.39.1` to `0.40.0` contains _major breaking changes_ that introduce major shifts in how ZenML code is written or used. ## Major Migration Guides The following guides contain detailed instructions on how to migrate between ZenML versions that introduced major breaking changes or paradigm shifts. The migration guides are sequential, meaning if there is more than one migration guide between your current version and the latest release, follow each guide in order. * [Migration guide 0.13.2 → 0.20.0](migration-zero-twenty.md) * [Migration guide 0.23.0 → 0.30.0](migration-zero-thirty.md) * [Migration guide 0.39.1 → 0.41.0](migration-zero-forty.md) * [Migration guide 0.58.2 → 0.60.0](migration-zero-sixty.md) ## Release Notes For releases with minor breaking changes, e.g., `0.40.3` to `0.41.0`, check out the official [ZenML Release Notes](https://github.com/zenml-io/zenml/releases) to see which breaking changes were introduced.
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/migration-guide/migration-zero-forty.md ================ --- description: How to migrate your ZenML pipelines and steps from version <=0.39.1 to 0.41.0. --- # Migration guide 0.39.1 → 0.41.0 ZenML versions 0.40.0 to 0.41.0 introduced a new and more flexible syntax to define ZenML steps and pipelines. This page contains code samples that show you how to upgrade your steps and pipelines to the new syntax. {% hint style="warning" %} Newer versions of ZenML still work with pipelines and steps defined using the old syntax, but the old syntax is deprecated and will be removed in the future. {% endhint %} ## Overview {% tabs %} {% tab title="Old Syntax" %} ```python from typing import Optional from zenml.steps import BaseParameters, Output, StepContext, step from zenml.pipelines import pipeline # Define a Step class MyStepParameters(BaseParameters): param_1: int param_2: Optional[float] = None @step def my_step( params: MyStepParameters, context: StepContext, ) -> Output(int_output=int, str_output=str): result = int(params.param_1 * (params.param_2 or 1)) result_uri = context.get_output_artifact_uri() return result, result_uri # Run the Step separately my_step.entrypoint() # Define a Pipeline @pipeline def my_pipeline(my_step): my_step() step_instance = my_step(params=MyStepParameters(param_1=17)) pipeline_instance = my_pipeline(my_step=step_instance) # Configure and run the Pipeline pipeline_instance.configure(enable_cache=False) schedule = Schedule(...) pipeline_instance.run(schedule=schedule) # Fetch the Pipeline Run last_run = pipeline_instance.get_runs()[0] int_output = last_run.get_step["my_step"].outputs["int_output"].read() ``` {% endtab %} {% tab title="New Syntax" %} ```python from typing import Annotated, Optional, Tuple from zenml import get_step_context, pipeline, step from zenml.client import Client # Define a Step @step def my_step( param_1: int, param_2: Optional[float] = None ) -> Tuple[Annotated[int, "int_output"], Annotated[str, "str_output"]]: result = int(param_1 * (param_2 or 1)) result_uri = get_step_context().get_output_artifact_uri() return result, result_uri # Run the Step separately my_step() # Define a Pipeline @pipeline def my_pipeline(): my_step(param_1=17) # Configure and run the Pipeline my_pipeline = my_pipeline.with_options(enable_cache=False, schedule=schedule) my_pipeline() # Fetch the Pipeline Run last_run = my_pipeline.last_run int_output = last_run.steps["my_step"].outputs["int_output"].load() ``` {% endtab %} {% endtabs %} ## Defining steps {% tabs %} {% tab title="Old Syntax" %} ```python from zenml.steps import step, BaseParameters from zenml.pipelines import pipeline # Old: Subclass `BaseParameters` to define parameters for a step class MyStepParameters(BaseParameters): param_1: int param_2: Optional[float] = None @step def my_step(params: MyStepParameters) -> None: ... @pipeline def my_pipeline(my_step): my_step() step_instance = my_step(params=MyStepParameters(param_1=17)) pipeline_instance = my_pipeline(my_step=step_instance) ``` {% endtab %} {% tab title="New Syntax" %} ```python # New: Directly define the parameters as arguments of your step function. # In case you still want to group your parameters in a separate class, # you can subclass `pydantic.BaseModel` and use that as an argument of your # step function from zenml import pipeline, step @step def my_step(param_1: int, param_2: Optional[float] = None) -> None: ... @pipeline def my_pipeline(): my_step(param_1=17) ``` {% endtab %} {% endtabs %} Check out [this page](../../pipeline-development/build-pipelines/use-pipeline-step-parameters.md) for more information on how to parameterize your steps. ## Calling a step outside of a pipeline {% tabs %} {% tab title="Old Syntax" %} ```python from zenml.steps import step @step def my_step() -> None: ... my_step.entrypoint() # Old: Call `step.entrypoint(...)` ``` {% endtab %} {% tab title="New Syntax" %} ```python from zenml import step @step def my_step() -> None: ... my_step() # New: Call the step directly `step(...)` ``` {% endtab %} {% endtabs %} ## Defining pipelines {% tabs %} {% tab title="Old Syntax" %} ```python from zenml.pipelines import pipeline @pipeline def my_pipeline(my_step): # Old: steps are arguments of the pipeline function my_step() ``` {% endtab %} {% tab title="New Syntax" %} ```python from zenml import pipeline, step @step def my_step() -> None: ... @pipeline def my_pipeline(): my_step() # New: The pipeline function calls the step directly ``` {% endtab %} {% endtabs %} ## Configuring pipelines {% tabs %} {% tab title="Old Syntax" %} ```python from zenml.pipelines import pipeline from zenml.steps import step @step def my_step() -> None: ... @pipeline def my_pipeline(my_step): my_step() # Old: Create an instance of the pipeline and then call `pipeline_instance.configure(...)` pipeline_instance = my_pipeline(my_step=my_step()) pipeline_instance.configure(enable_cache=False) ``` {% endtab %} {% tab title="New Syntax" %} ```python from zenml import pipeline, step @step def my_step() -> None: ... @pipeline def my_pipeline(): my_step() # New: Call the `with_options(...)` method on the pipeline my_pipeline = my_pipeline.with_options(enable_cache=False) ``` {% endtab %} {% endtabs %} ## Running pipelines {% tabs %} {% tab title="Old Syntax" %} ```python from zenml.pipelines import pipeline from zenml.steps import step @step def my_step() -> None: ... @pipeline def my_pipeline(my_step): my_step() # Old: Create an instance of the pipeline and then call `pipeline_instance.run(...)` pipeline_instance = my_pipeline(my_step=my_step()) pipeline_instance.run(...) ``` {% endtab %} {% tab title="New Syntax" %} ```python from zenml import pipeline, step @step def my_step() -> None: ... @pipeline def my_pipeline(): my_step() my_pipeline() # New: Call the pipeline ``` {% endtab %} {% endtabs %} ## Scheduling pipelines {% tabs %} {% tab title="Old Syntax" %} ```python from zenml.pipelines import pipeline, Schedule from zenml.steps import step @step def my_step() -> None: ... @pipeline def my_pipeline(my_step): my_step() # Old: Create an instance of the pipeline and then call `pipeline_instance.run(schedule=...)` schedule = Schedule(...) pipeline_instance = my_pipeline(my_step=my_step()) pipeline_instance.run(schedule=schedule) ``` {% endtab %} {% tab title="New Syntax" %} ```python from zenml.pipelines import Schedule from zenml import pipeline, step @step def my_step() -> None: ... @pipeline def my_pipeline(): my_step() # New: Set the schedule using the `pipeline.with_options(...)` method and then run it schedule = Schedule(...) my_pipeline = my_pipeline.with_options(schedule=schedule) my_pipeline() ``` {% endtab %} {% endtabs %} Check out [this page](../../pipeline-development/build-pipelines/schedule-a-pipeline.md) for more information on how to schedule your pipelines. ## Fetching pipelines after execution {% tabs %} {% tab title="Old Syntax" %} ```python pipeline: PipelineView = zenml.post_execution.get_pipeline("first_pipeline") last_run: PipelineRunView = pipeline.runs[0] # OR: last_run = my_pipeline.get_runs()[0] model_trainer_step: StepView = last_run.get_step("model_trainer") model: ArtifactView = model_trainer_step.output loaded_model = model.read() ``` {% endtab %} {% tab title="New Syntax" %} ```python pipeline: PipelineResponseModel = zenml.client.Client().get_pipeline("first_pipeline") # OR: pipeline = pipeline_instance.model last_run: PipelineRunResponseModel = pipeline.last_run # OR: last_run = pipeline.runs[0] # OR: last_run = pipeline.get_runs(custom_filters)[0] # OR: last_run = pipeline.last_successful_run model_trainer_step: StepRunResponseModel = last_run.steps["model_trainer"] model: ArtifactResponseModel = model_trainer_step.output loaded_model = model.load() ``` {% endtab %} {% endtabs %} Check out [this page](../../model-management-metrics/track-metrics-metadata/fetch-metadata-within-steps.md) for more information on how to programmatically fetch information about previous pipeline runs. ## Controlling the step execution order {% tabs %} {% tab title="Old Syntax" %} ```python from zenml.pipelines import pipeline @pipeline def my_pipeline(step_1, step_2, step_3): step_1() step_2() step_3() step_3.after(step_1) # Old: Use the `step.after(...)` method step_3.after(step_2) ``` {% endtab %} {% tab title="New Syntax" %} ```python from zenml import pipeline @pipeline def my_pipeline(): step_1() step_2() step_3(after=["step_1", "step_2"]) # New: Pass the `after` argument when calling a step ``` {% endtab %} {% endtabs %} Check out [this page](../../pipeline-development/build-pipelines/control-execution-order-of-steps.md) for more information on how to control the step execution order. ## Defining steps with multiple outputs {% tabs %} {% tab title="Old Syntax" %} ```python # Old: Use the `Output` class from zenml.steps import step, Output @step def my_step() -> Output(int_output=int, str_output=str): ... ``` {% endtab %} {% tab title="New Syntax" %} ```python # New: Use a `Tuple` annotation and optionally assign custom output names from typing_extensions import Annotated from typing import Tuple from zenml import step # Default output names `output_0`, `output_1` @step def my_step() -> Tuple[int, str]: ... # Custom output names @step def my_step() -> Tuple[ Annotated[int, "int_output"], Annotated[str, "str_output"], ]: ... ``` {% endtab %} {% endtabs %} Check out [this page](../../pipeline-development/build-pipelines/step-output-typing-and-annotation.md) for more information on how to annotate your step outputs. ## Accessing run information inside steps {% tabs %} {% tab title="Old Syntax" %} ```python from zenml.steps import StepContext, step from zenml.environment import Environment @step def my_step(context: StepContext) -> Any: # Old: `StepContext` class defined as arg env = Environment().step_environment output_uri = context.get_output_artifact_uri() step_name = env.step_name # Old: Run info accessible via `StepEnvironment` ... ``` {% endtab %} {% tab title="New Syntax" %} ```python from zenml import get_step_context, step @step def my_step() -> Any: # New: StepContext is no longer an argument of the step context = get_step_context() output_uri = context.get_output_artifact_uri() step_name = context.step_name # New: StepContext now has ALL run/step info ... ``` {% endtab %} {% endtabs %} Check out [this page](../../model-management-metrics/track-metrics-metadata/fetch-metadata-within-steps.md) for more information on how to fetch run information inside your steps using `get_step_context()`.
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/migration-guide/migration-zero-sixty.md ================ --- description: How to migrate from ZenML 0.58.2 to 0.60.0 (Pydantic 2 edition). --- # Release Notes ZenML now uses Pydantic v2. 🥳 This upgrade comes with a set of critical updates. While your user experience mostly remains unaffected, you might see unexpected behavior due to the changes in our dependencies. Moreover, since Pydantic v2 provides a slightly stricter validation process, you might end up bumping into some validation errors which was not caught before, but it is all for the better 🙂 If you run into any other errors, please let us know either on [GitHub](https://github.com/zenml-io/zenml) or on our [Slack](https://zenml.io/slack-invite). ## Changes in some of the critical dependencies - SQLModel is one of the core dependencies of ZenML and prior to this upgrade, we were utilizing version `0.0.8`. However, this version is relatively outdated and incompatible with Pydantic v2. Within the scope of this upgrade, we upgraded it to `0.0.18`. - Due to the change in the SQLModel version, we also had to upgrade our SQLAlchemy dependency from V1 to v2. While this does not affect the way that you are using ZenML, if you are using SQLAlchemy in your environment, you might have to migrate your code as well. For a detailed list of changes, feel free to check [their migration guide](https://docs.sqlalchemy.org/en/20/changelog/migration_20.html). ## Changes in `pydantic` Pydantic v2 brings a lot of new and exciting changes to the table. The core logic now uses Rust and it is much faster and more efficient in terms of performance. On top of it, the main concepts like model design, configuration, validation, or serialization now include a lot of new cool features. If you are using `pydantic` in your workflow and are interested in the new changes, you can check [the brilliant migration guide](https://docs.pydantic.dev/2.7/migration/) provided by the `pydantic` team to see the full list of changes. ## Changes in our integrations changes Much like ZenML, `pydantic` is an important dependency in many other Python packages. That’s why conducting this upgrade helped us unlock a new version for several ZenML integration dependencies. Additionally, in some instances, we had to adapt the functionality of the integration to keep it compatible with `pydantic`. So, if you are using any of these integrations, please go through the changes. ### Airflow As mentioned above upgrading our `pydantic` dependency meant we had to upgrade our `sqlmodel` dependency. Upgrading our `sqlmodel` dependency meant we had to upgrade our `sqlalchemy` dependency as well. Unfortunately, `apache-airflow` is still using `sqlalchemy` v1 and is incompatible with pydantic v2. As a solution, we have removed the dependencies of the `airflow` integration. Now, you can use ZenML to create your Airflow pipelines and use a separate environment to run them with Airflow. You can check the updated docs [right here](../../../component-guide/orchestrators/airflow.md). ### AWS Some of our integrations now require `protobuf` 4. Since our previous `sagemaker` version (`2.117.0`) did not support `protobof` 4, we could not pair it with these new integrations. Thankfully `sagemaker` started supporting `protobuf` 4 with version `2.172.0` and relaxing its dependency solved the compatibility issue. ### Evidently The old version of our `evidently` integration was not compatible with Pydantic v2. They started supporting it starting from version `0.4.16`. As their latest version is `0.4.22`, the new dependency of the integration is limited between these two versions. ### Feast Our previous implementation of the `feast` integration was not compatible with Pydantic v2 due to the extra `redis` dependency we were using. This extra dependency is now removed and the `feast` integration is working as intended. ### GCP The previous version of the Kubeflow dependency (`kfp==1.8.22`) in our GCP integration required Pydantic V1 to be installed. While we were upgrading our Pydantic dependency, we saw this as an opportunity and wanted to use this chance to upgrade the `kfp` dependency to v2 (which has no dependencies on the Pydantic library). This is why you may see some functional changes in the vertex step operator and orchestrator. If you would like to go through the changes in the `kfp` library, you can find [the migration guide here](https://www.kubeflow.org/docs/components/pipelines/v2/migration/). ### Great Expectations Great Expectations started supporting Pydantic v2 starting from version `0.17.15` and they are closing in on their `1.0` release. Since this release might include a lot of big changes, we adjusted the dependency in our integration to `great-expectations>=0.17.15,<1.0`. We will try to keep it updated in the future once they release the `1.0` version ### Kubeflow Similar to the GCP integration, the previous version of the kubeflow dependency (`kfp==1.8.22`) in our `kubeflow` integration required Pydantic V1 to be installed. While we were upgrading our Pydantic dependency, we saw this as an opportunity and wanted to use this chance to upgrade the `kfp` dependency to v2 (which has no dependencies on the Pydantic library). If you would like to go through the changes in the `kfp` library, you can find [the migration guide here](https://www.kubeflow.org/docs/components/pipelines/v2/migration/). ( We also are considering adding an alternative version of this integration so our users can keep using `kfp` V1 in their environment. Stay tuned for any updates.) ### MLflow `mlflow` is compatible with both Pydantic V1 and v2. However, due to a known issue, if you install `zenml` first and then do `zenml integration install mlflow -y`, it downgrades `pydantic` to V1. This is why we manually added the same duplicated `pydantic` requirement in the integration definition as well. Keep in mind that the `mlflow` library is still using some features of `pydantic` V1 which are deprecated. So, if the integration is installed in your environment, you might run into some deprecation warnings. ### Label Studio While we were working on updating our `pydantic` dependency, the `label-studio-sdk` has released its 1.0 version. In this new version, `pydantic` v2 is also supported. The implementation and documentation of our Label Studio integration have been updated accordingly. ### Skypilot With the switch to `pydantic` v2, the implementation of our `skypilot` integration mostly remained untouched. However, due to an incompatibility between the new version `pydantic` and the `azurecli`, the `skypilot[azure]` flavor can not be installed at the same time, thus our `skypilot_azure` integration is currently deactivated. We are working on fixing this issue and if you are using this integration in your workflows, we recommend staying on the previous version of ZenML until we can solve this issue. ### Tensorflow The new version of `pydantic` creates a drift between `tensorflow` and `typing_extensions` packages and relaxing the dependencies here resolves the issue. At the same time, the upgrade to `kfp` v2 (in integrations like `kubeflow`, `tekton`, or `gcp`) bumps our `protobuf` dependency from `3.X` to `4.X`. To stay compatible with this requirement, the installed version of `tensorflow` needs to be `>=2.12.0`. While this change solves the dependency issues in most settings, we have bumped into some errors while using `tensorflow` 2.12.0 on Python 3.8 on Ubuntu. If you would like to use this integration, please consider using a higher Python version. ### Tekton Similar to the `gcp` and `kubeflow` integrations, the old version of our `tekton` integration was not compatible with `pydantic` V1 due to its `kfp` dependency. With the switch from `kfp` V1 to v2, we have adapted our implementation to use the new version of `kfp` library and updated our documentation accordingly. {% hint style="warning" %} Due to all aforementioned changes, when you upgrade ZenML to 0.60.0, you might run into some dependency issues, especially if you were previously using an integration which was not supporting Pydantic v2 before. In such cases, we highly recommend setting up a fresh Python environment. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/migration-guide/migration-zero-thirty.md ================ --- description: How to migrate from ZenML 0.20.0-0.23.0 to 0.30.0-0.39.1. --- {% hint style="warning" %} Migrating to `0.30.0` performs non-reversible database changes so downgrading to `<=0.23.0` is not possible afterwards. If you are running on an older ZenML version, please follow the [0.20.0 Migration Guide](migration-zero-twenty.md) first to prevent unexpected database migration failures. {% endhint %} The ZenML 0.30.0 release removed the `ml-pipelines-sdk` dependency in favor of natively storing pipeline runs and artifacts in the ZenML database. The corresponding database migration will happen automatically as soon as you run any `zenml ...` CLI command after installing the new ZenML version, e.g.: ```bash pip install zenml==0.30.0 zenml version # 0.30.0 ```
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/migration-guide/migration-zero-twenty.md ================ --- description: How to migrate from ZenML <=0.13.2 to 0.20.0. --- # Migration guide 0.13.2 → 0.20.0 *Last updated: 2023-07-24* The ZenML 0.20.0 release brings a number of big changes to its architecture and its features, some of which are not backwards compatible with previous versions. This guide walks you through these changes and offers instructions on how to migrate your existing ZenML stacks and pipelines to the new version with minimal effort and disruption to your existing workloads. {% hint style="warning" %} Updating to ZenML 0.20.0 needs to be followed by a migration of your existing ZenML Stacks and you may also need to make changes to your current ZenML pipeline code. Please read this guide carefully and follow the migration instructions to ensure a smooth transition. If you have updated to ZenML 0.20.0 by mistake or are experiencing issues with the new version, you can always go back to the previous version by using `pip install zenml==0.13.2` instead of `pip install zenml` when installing ZenML manually or in your scripts. {% endhint %} High-level overview of the changes: * [ZenML takes over the Metadata Store](migration-zero-twenty.md#zenml-takes-over-the-metadata-store-role) role. All information about your ZenML Stacks, pipelines, and artifacts is tracked by ZenML itself directly. If you are currently using remote Metadata Stores (e.g. deployed in cloud) in your stacks, you will probably need to replace them with a [ZenML server deployment](../../../getting-started/deploying-zenml/README.md). * the [new ZenML Dashboard](migration-zero-twenty.md#the-zenml-dashboard-is-now-available) is now available with all ZenML deployments. * [ZenML Profiles have been removed](migration-zero-twenty.md#removal-of-profiles-and-the-local-yaml-database) in favor of ZenML Projects. You need to [manually migrate your existing ZenML Profiles](migration-zero-twenty.md#-how-to-migrate-your-profiles) after the update. * the [configuration of Stack Components is now decoupled from their implementation](migration-zero-twenty.md#decoupling-stack-component-configuration-from-implementation). If you extended ZenML with custom stack component implementations, you may need to update the way they are registered in ZenML. * the updated ZenML server provides a new and improved collaborative experience. When connected to a ZenML server, you can now [share your ZenML Stacks and Stack Components](migration-zero-twenty.md#shared-zenml-stacks-and-stack-components) with other users. If you were previously using the ZenML Profiles or the ZenML server to share your ZenML Stacks, you should switch to the new ZenML server and Dashboard and update your existing workflows to reflect the new features. ## ZenML takes over the Metadata Store role ZenML can now run [as a server](../../../getting-started/core-concepts.md#zenml-server-and-dashboard) that can be accessed via a REST API and also comes with a visual user interface (called the ZenML Dashboard). This server can be deployed in arbitrary environments (local, on-prem, via Docker, on AWS, GCP, Azure etc.) and supports user management, workspace scoping, and more. The release introduces a series of commands to facilitate managing the lifecycle of the ZenML server and to access the pipeline and pipeline run information: * `zenml connect / disconnect / down / up / logs / status` can be used to configure your client to connect to a ZenML server, to start a local ZenML Dashboard or to deploy a ZenML server to a cloud environment. For more information on how to use these commands, see [the ZenML deployment documentation](../../../getting-started/deploying-zenml/README.md). * `zenml pipeline list / runs / delete` can be used to display information and about and manage your pipelines and pipeline runs. In ZenML 0.13.2 and earlier versions, information about pipelines and pipeline runs used to be stored in a separate stack component called the Metadata Store. Starting with 0.20.0, the role of the Metadata Store is now taken over by ZenML itself. This means that the Metadata Store is no longer a separate component in the ZenML architecture, but rather a part of the ZenML core, located wherever ZenML is deployed: locally on your machine or running remotely as a server. All metadata is now stored, tracked, and managed by ZenML itself. The Metadata Store stack component type and all its implementations have been deprecated and removed. It is no longer possible to register them or include them in ZenML stacks. This is a key architectural change in ZenML 0.20.0 that further improves usability, reproducibility and makes it possible to visualize and manage all your pipelines and pipeline runs in the new ZenML Dashboard. The architecture changes for the local case are shown in the diagram below: ![ZenML local metadata before 0.20.0](../../user-guide/assets/migration/local-metadata-pre-0.20.png) ![ZenML local metadata after 0.20.0](../../user-guide/assets/migration/local-metadata-post-0.20.png) The architecture changes for the remote case are shown in the diagram below: ![ZenML remote metadata before 0.20.0](../../user-guide/assets/migration/remote-metadata-pre-0.20.png) ![ZenML remote metadata after 0.20.0](../../user-guide/assets/migration/remote-metadata-post-0.20.png) If you're already using ZenML, aside from the above limitation, this change will impact you differently, depending on the flavor of Metadata Stores you have in your stacks: * if you're using the default `sqlite` Metadata Store flavor in your stacks, you don't need to do anything. ZenML will automatically switch to using its local database instead of your `sqlite` Metadata Stores when you update to 0.20.0 (also see how to [migrate your stacks](migration-zero-twenty.md#-how-to-migrate-your-profiles)). * if you're using the `kubeflow` Metadata Store flavor _only as a way to connect to the local Kubeflow Metadata Service_ (i.e. the one installed by the `kubeflow` Orchestrator in a local k3d Kubernetes cluster), you also don't need to do anything explicitly. When you [migrate your stacks](migration-zero-twenty.md#-how-to-migrate-your-profiles) to ZenML 0.20.0, ZenML will automatically switch to using its local database. * if you're using the `kubeflow` Metadata Store flavor to connect to a remote Kubeflow Metadata Service such as those provided by a Kubeflow installation running in AWS, Google or Azure, there is currently no equivalent in ZenML 0.20.0. You'll need to [deploy a ZenML Server](../../../getting-started/deploying-zenml/README.md) instance close to where your Kubeflow service is running (e.g. in the same cloud region). * if you're using the `mysql` Metadata Store flavor to connect to a remote MySQL database service (e.g. a managed AWS, GCP or Azure MySQL service), you'll have to [deploy a ZenML Server](../../../getting-started/deploying-zenml/README.md) instance connected to that same database. * if you deployed a `kubernetes` Metadata Store flavor (i.e. a MySQL database service deployed in Kubernetes), you can [deploy a ZenML Server](../../../getting-started/deploying-zenml/README.md) in the same Kubernetes cluster and connect it to that same database. However, ZenML will no longer provide the `kubernetes` Metadata Store flavor and you'll have to manage the Kubernetes MySQL database service deployment yourself going forward. {% hint style="info" %} The ZenML Server inherits the same limitations that the Metadata Store had prior to ZenML 0.20.0: * it is not possible to use a local ZenML Server to track pipelines and pipeline runs that are running remotely in the cloud, unless the ZenML server is explicitly configured to be reachable from the cloud (e.g. by using a public IP address or a VPN connection). * using a remote ZenML Server to track pipelines and pipeline runs that are running locally is possible, but can have significant performance issues due to the network latency. It is therefore recommended that you always use a ZenML deployment that is located as close as possible to and reachable from where your pipelines and step operators are running. This will ensure the best possible performance and usability. {% endhint %} ### 👣 How to migrate pipeline runs from your old metadata stores {% hint style="info" %} The `zenml pipeline runs migrate` CLI command is only available under ZenML versions \[0.21.0, 0.21.1, 0.22.0]. If you want to migrate your existing ZenML runs from `zenml<0.20.0` to `zenml>0.22.0`, please first upgrade to `zenml==0.22.0` and migrate your runs as shown below, then upgrade to the newer version. {% endhint %} To migrate the pipeline run information already stored in an existing metadata store to the new ZenML paradigm, you can use the `zenml pipeline runs migrate` CLI command. 1. Before upgrading ZenML, make a backup of all metadata stores you want to migrate, then upgrade ZenML. 2. Decide the ZenML deployment model that you want to follow for your projects. See the [ZenML deployment documentation](../../../getting-started/deploying-zenml/README.md) for available deployment scenarios. If you decide on using a local or remote ZenML server to manage your pipelines, make sure that you first connect your client to it by running `zenml connect`. 3. Use the `zenml pipeline runs migrate` CLI command to migrate your old pipeline runs: * If you want to migrate from a local SQLite metadata store, you only need to pass the path to the metadata store to the command, e.g.: ```bash zenml pipeline runs migrate PATH/TO/LOCAL/STORE/metadata.db ``` * If you would like to migrate any other store, you will need to set `--database_type=mysql` and provide the MySQL host, username, and password in addition to the database, e.g.: ```bash zenml pipeline runs migrate DATABASE_NAME \ --database_type=mysql \ --mysql_host=URL/TO/MYSQL \ --mysql_username=MYSQL_USERNAME \ --mysql_password=MYSQL_PASSWORD ``` ### 💾 The New Way (CLI Command Cheat Sheet) **Deploy the server** `zenml deploy --aws` (maybe don’t do this :) since it spins up infrastructure on AWS…) **Spin up a local ZenML Server** `zenml up` **Connect to a pre-existing server** `zenml connect` (pass in URL / etc, or zenml connect --config + yaml file) **List your deployed server details** `zenml status` ## The ZenML Dashboard is now available The new ZenML Dashboard is now bundled into the ZenML Python package and can be launched directly from Python. The source code lives in the [ZenML Dashboard repository](https://github.com/zenml-io/zenml-dashboard). To launch it locally, simply run `zenml up` on your machine and follow the instructions: ```bash $ zenml up Deploying a local ZenML server with name 'local'. Connecting ZenML to the 'local' local ZenML server (http://127.0.0.1:8237). Updated the global store configuration. Connected ZenML to the 'local' local ZenML server (http://127.0.0.1:8237). The local ZenML dashboard is available at 'http://127.0.0.1:8237'. You can connect to it using the 'default' username and an empty password. ``` The Dashboard will be available at `http://localhost:8237` by default: ![ZenML Dashboard Preview](../../user-guide/assets/migration/zenml-dashboard.png) For more details on other possible deployment options, see the [ZenML deployment documentation](../../../getting-started/deploying-zenml/README.md), and/or follow the [starter guide](../../../user-guide/starter-guide/README.md) to learn more. ## Removal of Profiles and the local YAML database Prior to 0.20.0, ZenML used used a set of local YAML files to store information about the Stacks and Stack Components that were registered on your machine. In addition to that, these Stacks could be grouped together and organized under individual Profiles. Profiles and the local YAML database have both been deprecated and removed in ZenML 0.20.0. Stack, Stack Components as well as all other information that ZenML tracks, such as Pipelines and Pipeline Runs, are now stored in a single SQL database. These entities are no longer organized into Profiles, but they can be scoped into different Projects instead. {% hint style="warning" %} Since the local YAML database is no longer used by ZenML 0.20.0, you will lose all the Stacks and Stack Components that you currently have configured when you update to ZenML 0.20.0. If you still want to use these Stacks, you will need to [manually migrate](migration-zero-twenty.md#-how-to-migrate-your-profiles) them after the update. {% endhint %} ### 👣 How to migrate your Profiles If you're already using ZenML, you can migrate your existing Profiles to the new ZenML 0.20.0 paradigm by following these steps: 1. first, update ZenML to 0.20.0. This will automatically invalidate all your existing Profiles. 2. decide the ZenML deployment model that you want to follow for your projects. See the [ZenML deployment documentation](../../../getting-started/deploying-zenml/README.md) for available deployment scenarios. If you decide on using a local or remote ZenML server to manage your pipelines, make sure that you first connect your client to it by running `zenml connect`. 3. use the `zenml profile list` and `zenml profile migrate` CLI commands to import the Stacks and Stack Components from your Profiles into your new ZenML deployment. If you have multiple Profiles that you would like to migrate, you can either use a prefix for the names of your imported Stacks and Stack Components, or you can use a different ZenML Project for each Profile. {% hint style="warning" %} The ZenML Dashboard is currently limited to showing only information that is available in the `default` Project. If you wish to migrate your Profiles to a different Project, you will not be able to visualize the migrated Stacks and Stack Components in the Dashboard. This will be fixed in a future release. {% endhint %} Once you've migrated all your Profiles, you can delete the old YAML files. Example of migrating a `default` profile into the `default` project: ```bash $ zenml profile list ZenML profiles have been deprecated and removed in this version of ZenML. All stacks, stack components, flavors etc. are now stored and managed globally, either in a local database or on a remote ZenML server (see the `zenml up` and `zenml connect` commands). As an alternative to profiles, you can use projects as a scoping mechanism for stacks, stack components and other ZenML objects. The information stored in legacy profiles is not automatically migrated. You can do so manually by using the `zenml profile list` and `zenml profile migrate` commands. Found profile with 1 stacks, 3 components and 0 flavors at: /home/stefan/.config/zenml/profiles/default Found profile with 3 stacks, 6 components and 0 flavors at: /home/stefan/.config/zenml/profiles/zenprojects Found profile with 3 stacks, 7 components and 0 flavors at: /home/stefan/.config/zenml/profiles/zenbytes $ zenml profile migrate /home/stefan/.config/zenml/profiles/default No component flavors to migrate from /home/stefan/.config/zenml/profiles/default/stacks.yaml... Migrating stack components from /home/stefan/.config/zenml/profiles/default/stacks.yaml... Created artifact_store 'cloud_artifact_store' with flavor 's3'. Created container_registry 'cloud_registry' with flavor 'aws'. Created container_registry 'local_registry' with flavor 'default'. Created model_deployer 'eks_seldon' with flavor 'seldon'. Created orchestrator 'cloud_orchestrator' with flavor 'kubeflow'. Created orchestrator 'kubeflow_orchestrator' with flavor 'kubeflow'. Created secrets_manager 'aws_secret_manager' with flavor 'aws'. Migrating stacks from /home/stefan/.config/zenml/profiles/v/stacks.yaml... Created stack 'cloud_kubeflow_stack'. Created stack 'local_kubeflow_stack'. $ zenml stack list Using the default local database. Running with active project: 'default' (global) ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┓ ┃ ACTIVE │ STACK NAME │ STACK ID │ SHARED │ OWNER │ CONTAINER_REGISTRY │ ARTIFACT_STORE │ ORCHESTRATOR │ MODEL_DEPLOYER │ SECRETS_MANAGER ┃ ┠────────┼──────────────────────┼──────────────────────────────────────┼────────┼─────────┼────────────────────┼──────────────────────┼───────────────────────┼────────────────┼────────────────────┨ ┃ │ local_kubeflow_stack │ 067cc6ee-b4da-410d-b7ed-06da4c983145 │ │ default │ local_registry │ default │ kubeflow_orchestrator │ │ ┃ ┠────────┼──────────────────────┼──────────────────────────────────────┼────────┼─────────┼────────────────────┼──────────────────────┼───────────────────────┼────────────────┼────────────────────┨ ┃ │ cloud_kubeflow_stack │ 054f5efb-9e80-48c0-852e-5114b1165d8b │ │ default │ cloud_registry │ cloud_artifact_store │ cloud_orchestrator │ eks_seldon │ aws_secret_manager ┃ ┠────────┼──────────────────────┼──────────────────────────────────────┼────────┼─────────┼────────────────────┼──────────────────────┼───────────────────────┼────────────────┼────────────────────┨ ┃ 👉 │ default │ fe913bb5-e631-4d4e-8c1b-936518190ebb │ │ default │ │ default │ default │ │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┛ ``` Example of migrating a profile into the `default` project using a name prefix: ```bash $ zenml profile migrate /home/stefan/.config/zenml/profiles/zenbytes --prefix zenbytes_ No component flavors to migrate from /home/stefan/.config/zenml/profiles/zenbytes/stacks.yaml... Migrating stack components from /home/stefan/.config/zenml/profiles/zenbytes/stacks.yaml... Created artifact_store 'zenbytes_s3_store' with flavor 's3'. Created container_registry 'zenbytes_ecr_registry' with flavor 'default'. Created experiment_tracker 'zenbytes_mlflow_tracker' with flavor 'mlflow'. Created experiment_tracker 'zenbytes_mlflow_tracker_local' with flavor 'mlflow'. Created model_deployer 'zenbytes_eks_seldon' with flavor 'seldon'. Created model_deployer 'zenbytes_mlflow' with flavor 'mlflow'. Created orchestrator 'zenbytes_eks_orchestrator' with flavor 'kubeflow'. Created secrets_manager 'zenbytes_aws_secret_manager' with flavor 'aws'. Migrating stacks from /home/stefan/.config/zenml/profiles/zenbytes/stacks.yaml... Created stack 'zenbytes_aws_kubeflow_stack'. Created stack 'zenbytes_local_with_mlflow'. $ zenml stack list Using the default local database. Running with active project: 'default' (global) ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ACTIVE │ STACK NAME │ STACK ID │ SHARED │ OWNER │ ORCHESTRATOR │ ARTIFACT_STORE │ CONTAINER_REGISTRY │ SECRETS_MANAGER │ MODEL_DEPLOYER │ EXPERIMENT_TRACKER ┃ ┠────────┼──────────────────────┼──────────────────────┼────────┼─────────┼───────────────────────┼───────────────────┼──────────────────────┼───────────────────────┼─────────────────────┼──────────────────────┨ ┃ │ zenbytes_aws_kubeflo │ 9fe90f0b-2a79-47d9-8 │ │ default │ zenbytes_eks_orchestr │ zenbytes_s3_store │ zenbytes_ecr_registr │ zenbytes_aws_secret_m │ zenbytes_eks_seldon │ ┃ ┃ │ w_stack │ f80-04e45ff02cdb │ │ │ ator │ │ y │ manager │ │ ┃ ┠────────┼──────────────────────┼──────────────────────┼────────┼─────────┼───────────────────────┼───────────────────┼──────────────────────┼───────────────────────┼─────────────────────┼──────────────────────┨ ┃ 👉 │ default │ 7a587e0c-30fd-402f-a │ │ default │ default │ default │ │ │ │ ┃ ┃ │ │ 3a8-03651fe1458f │ │ │ │ │ │ │ │ ┃ ┠────────┼──────────────────────┼──────────────────────┼────────┼─────────┼───────────────────────┼───────────────────┼──────────────────────┼───────────────────────┼─────────────────────┼──────────────────────┨ ┃ │ zenbytes_local_with_ │ c2acd029-8eed-4b6e-a │ │ default │ default │ default │ │ │ zenbytes_mlflow │ zenbytes_mlflow_trac ┃ ┃ │ mlflow │ d19-91c419ce91d4 │ │ │ │ │ │ │ │ ker ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┛ ``` Example of migrating a profile into a new project: ```bash $ zenml profile migrate /home/stefan/.config/zenml/profiles/zenprojects --project zenprojects Unable to find ZenML repository in your current working directory (/home/stefan/aspyre/src/zenml) or any parent directories. If you want to use an existing repository which is in a different location, set the environment variable 'ZENML_REPOSITORY_PATH'. If you want to create a new repository, run zenml init. Running without an active repository root. Creating project zenprojects Creating default stack for user 'default' in project zenprojects... No component flavors to migrate from /home/stefan/.config/zenml/profiles/zenprojects/stacks.yaml... Migrating stack components from /home/stefan/.config/zenml/profiles/zenprojects/stacks.yaml... Created artifact_store 'cloud_artifact_store' with flavor 's3'. Created container_registry 'cloud_registry' with flavor 'aws'. Created container_registry 'local_registry' with flavor 'default'. Created model_deployer 'eks_seldon' with flavor 'seldon'. Created orchestrator 'cloud_orchestrator' with flavor 'kubeflow'. Created orchestrator 'kubeflow_orchestrator' with flavor 'kubeflow'. Created secrets_manager 'aws_secret_manager' with flavor 'aws'. Migrating stacks from /home/stefan/.config/zenml/profiles/zenprojects/stacks.yaml... Created stack 'cloud_kubeflow_stack'. Created stack 'local_kubeflow_stack'. $ zenml project set zenprojects Currently the concept of `project` is not supported within the Dashboard. The Project functionality will be completed in the coming weeks. For the time being it is recommended to stay within the `default` project. Using the default local database. Running with active project: 'default' (global) Set active project 'zenprojects'. $ zenml stack list Using the default local database. Running with active project: 'zenprojects' (global) The current global active stack is not part of the active project. Resetting the active stack to default. You are running with a non-default project 'zenprojects'. Any stacks, components, pipelines and pipeline runs produced in this project will currently not be accessible through the dashboard. However, this will be possible in the near future. ┏━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━┓ ┃ ACTIVE │ STACK NAME │ STACK ID │ SHARED │ OWNER │ ARTIFACT_STORE │ ORCHESTRATOR │ MODEL_DEPLOYER │ CONTAINER_REGISTRY │ SECRETS_MANAGER ┃ ┠────────┼──────────────────────┼──────────────────────────────────────┼────────┼─────────┼──────────────────────┼───────────────────────┼────────────────┼────────────────────┼────────────────────┨ ┃ 👉 │ default │ 3ea77330-0c75-49c8-b046-4e971f45903a │ │ default │ default │ default │ │ │ ┃ ┠────────┼──────────────────────┼──────────────────────────────────────┼────────┼─────────┼──────────────────────┼───────────────────────┼────────────────┼────────────────────┼────────────────────┨ ┃ │ cloud_kubeflow_stack │ b94df4d2-5b65-4201-945a-61436c9c5384 │ │ default │ cloud_artifact_store │ cloud_orchestrator │ eks_seldon │ cloud_registry │ aws_secret_manager ┃ ┠────────┼──────────────────────┼──────────────────────────────────────┼────────┼─────────┼──────────────────────┼───────────────────────┼────────────────┼────────────────────┼────────────────────┨ ┃ │ local_kubeflow_stack │ 8d9343ac-d405-43bd-ab9c-85637e479efe │ │ default │ default │ kubeflow_orchestrator │ │ local_registry │ ┃ ┗━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━┛ ``` The `zenml profile migrate` CLI command also provides command line flags for cases in which the user wants to overwrite existing components or stacks, or ignore errors. ## Decoupling Stack Component configuration from implementation Stack components can now be registered without having the required integrations installed. As part of this change, we split all existing stack component definitions into three classes: an implementation class that defines the logic of the stack component, a config class that defines the attributes and performs input validations, and a flavor class that links implementation and config classes together. See [**component flavor models #895**](https://github.com/zenml-io/zenml/pull/895) for more details. If you are only using stack component flavors that are shipped with the zenml Python distribution, this change has no impact on the configuration of your existing stacks. However, if you are currently using custom stack component implementations, you will need to update them to the new format. See the [documentation on writing custom stack component flavors](../../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md) for updated information on how to do this. ## Shared ZenML Stacks and Stack Components With collaboration being the key part of ZenML, the 0.20.0 release puts the concepts of Users in the front and center and introduces the possibility to share stacks and stack components with other users by means of the ZenML server. When your client is connected to a ZenML server, entities such as Stacks, Stack Components, Stack Component Flavors, Pipelines, Pipeline Runs, and artifacts are scoped to a Project and owned by the User that creates them. Only the objects that are owned by the current user used to authenticate to the ZenML server and that are part of the current project are available to the client. Stacks and Stack Components can also be shared within the same project with other users. To share an object, either set it as shared during creation time (e.g. `zenml stack register mystack ... --share`) or afterwards (e.g. through `zenml stack share mystack`). To differentiate between shared and private Stacks and Stack Components, these can now be addressed by name, id or the first few letters of the id in the cli. E.g. for a stack `default` with id `179ebd25-4c5b-480f-a47c-d4f04e0b6185` you can now run `zenml stack describe default` or `zenml stack describe 179` or `zenml stack describe 179ebd25-4c5b-480f-a47c-d4f04e0b6185`. We also introduce the notion of `local` vs `non-local` stack components. Local stack components are stack components that are configured to run locally while non-local stack components are configured to run remotely or in a cloud environment. Consequently: * stacks made up of local stack components should not be shared on a central ZenML Server, even though this is not enforced by the system. * stacks made up of non-local stack components are only functional if they are shared through a remotely deployed ZenML Server. Read more about shared stacks in the new [starter guide](../../user-guide/starter-guide/stacks/managing-stacks.md#sharing-stacks-over-a-zenml-server). ## Other changes ### The `Repository` class is now called `Client` The `Repository` object has been renamed to `Client` to better capture its functionality. You can continue to use the `Repository` object for backwards compatibility, but it will be removed in a future release. **How to migrate**: Rename all references to `Repository` in your code to `Client`. ### The `BaseStepConfig` class is now called `BaseParameters` The `BaseStepConfig` object has been renamed to `BaseParameters` to better capture its functionality. You can NOT continue to use the `BaseStepConfig`. This is part of a broader configuration rehaul which is discussed next. **How to migrate**: Rename all references to `BaseStepConfig` in your code to `BaseParameters`. ### Configuration Rework Alongside the architectural shift, Pipeline configuration has been completely rethought. This video gives an overview of how configuration has changed with ZenML in the post ZenML 0.20.0 world. {% embed url="https://www.youtube.com/embed/hI-UNV7uoNI" %} Configuring pipelines, steps, and stack components in ZenML {% endembed %} **What changed?** ZenML pipelines and steps could previously be configured in many different ways: * On the `@pipeline` and `@step` decorators (e.g. the `requirements` variable) * In the `__init__` method of the pipeline and step class * Using `@enable_xxx` decorators, e.g. `@enable_mlflow`. * Using specialized methods like `pipeline.with_config(...)` or `step.with_return_materializer(...)` Some of the configuration options were quite hidden, difficult to access and not tracked in any way by the ZenML metadata store. With ZenML 0.20.0, we introduce the `BaseSettings` class, a broad class that serves as a central object to represent all runtime configuration of a pipeline run (apart from the `BaseParameters`). Pipelines and steps now allow all configurations on their decorators as well as the `.configure(...)` method. This includes configurations for stack components that are not infrastructure-related which was previously done using the `@enable_xxx` decorators). The same configurations can also be defined in a YAML file. Read more about this paradigm in the [new docs section about settings](../../../how-to/pipeline-development/use-configuration-files/what-can-be-configured.md). Here is a list of changes that are the most obvious in consequence of the above code. Please note that this list is not exhaustive, and if we have missed something let us know via [Slack](https://zenml.io/slack). **Deprecating the `enable_xxx` decorators** With the above changes, we are deprecating the much-loved `enable_xxx` decorators, like `enable_mlflow` and `enable_wandb`. **How to migrate**: Simply remove the decorator and pass something like this instead to step directly: ```python @step( experiment_tracker="mlflow_stack_comp_name", # name of registered component settings={ # settings of registered component "experiment_tracker.mlflow": { # this is `category`.`flavor`, so another example is `step_operator.spark` "experiment_name": "name", "nested": False } } ) ``` **Deprecating `pipeline.with_config(...)`** **How to migrate**: Replaced with the new `pipeline.run(config_path=...)`. **Deprecating `step.with_return_materializer(...)`** **How to migrate**: Simply remove the `with_return_materializer` method and pass something like this instead to step directly: ```python @step( output_materializers=materializer_or_dict_of_materializers_mapped_to_outputs ) ``` **`DockerConfiguration` is now renamed to `DockerSettings`** **How to migrate**: Rename `DockerConfiguration` to `DockerSettings` and instead of passing it in the decorator directly with `docker_configuration`, you can use: ```python from zenml.config import DockerSettings @step(settings={"docker": DockerSettings(...)}) def my_step() -> None: ... ``` With this change, all stack components (e.g. Orchestrators and Step Operators) that accepted a `docker_parent_image` as part of its Stack Configuration should now pass it through the `DockerSettings` object. Read more [here](../../../how-to/customize-docker-builds/docker-settings-on-a-pipeline.md). **`ResourceConfiguration` is now renamed to `ResourceSettings`** **How to migrate**: Rename `ResourceConfiguration` to `ResourceSettings` and instead of passing it in the decorator directly with `resource_configuration`, you can use: ```python from zenml.config import ResourceSettings @step(settings={"resources": ResourceSettings(...)}) def my_step() -> None: ... ``` **Deprecating the `requirements` and `required_integrations` parameters** Users used to be able to pass `requirements` and `required_integrations` directly in the `@pipeline` decorator, but now need to pass them through settings: **How to migrate**: Simply remove the parameters and use the `DockerSettings` instead ```python from zenml.config import DockerSettings @step(settings={"docker": DockerSettings(requirements=[...], requirements_integrations=[...])}) def my_step() -> None: ... ``` Read more [here](../../../how-to/customize-docker-builds/README.md). **A new pipeline intermediate representation** All the aforementioned configurations as well as additional information required to run a ZenML pipelines are now combined into an intermediate representation called `PipelineDeployment`. Instead of the user-facing `BaseStep` and `BasePipeline` classes, all the ZenML orchestrators and step operators now use this intermediate representation to run pipelines and steps. **How to migrate**: If you have written a [custom orchestrator](../../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md) or [step operator](../../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md), then you should see the new base abstractions (seen in the links). You can adjust your stack component implementations accordingly. ### `PipelineSpec` now uniquely defines pipelines Once a pipeline has been executed, it is represented by a `PipelineSpec` that uniquely identifies it. Therefore, users are no longer able to edit a pipeline once it has been run once. There are now three options to get around this: * Pipeline runs can be created without being associated with a pipeline explicitly: We call these `unlisted` runs. Read more about unlisted runs [here](../../../how-to/pipeline-development/parameters-and-caching.md#unlisted-runs). * Pipelines can be deleted and created again. * Pipelines can be given unique names each time they are run to uniquely identify them. **How to migrate**: No code changes, but rather keep in mind the behavior (e.g. in a notebook setting) when quickly [iterating over pipelines as experiments](../../../how-to/pipeline-development/build-pipelines/use-pipeline-step-parameters.md). ### New post-execution workflow The Post-execution workflow has changed as follows: * The `get_pipelines` and `get_pipeline` methods have been moved out of the `Repository` (i.e. the new `Client` ) class and lie directly in the post\_execution module now. To use the user has to do: ```python from zenml.post_execution import get_pipelines, get_pipeline ``` * New methods to directly get a run have been introduced: `get_run` and `get_unlisted_runs` method has been introduced to get unlisted runs. Usage remains largely similar. Please read the [new docs for post-execution](../../../how-to/pipeline-development/build-pipelines/fetching-pipelines.md) to inform yourself of what further has changed. **How to migrate**: Replace all post-execution workflows from the paradigm of `Repository.get_pipelines` or `Repository.get_pipeline_run` to the corresponding post\_execution methods. ## 📡Future Changes While this rehaul is big and will break previous releases, we do have some more work left to do. However we also expect this to be the last big rehaul of ZenML before our 1.0.0 release, and no other release will be so hard breaking as this one. Currently planned future breaking changes are: * Following the metadata store, the secrets manager stack component might move out of the stack. * ZenML `StepContext` might be deprecated. ## 🐞 Reporting Bugs While we have tried our best to document everything that has changed, we realize that mistakes can be made and smaller changes overlooked. If this is the case, or you encounter a bug at any time, the ZenML core team and community are available around the clock on the growing [Slack community](https://zenml.io/slack). For bug reports, please also consider submitting a [GitHub Issue](https://github.com/zenml-io/zenml/issues/new/choose). Lastly, if the new changes have left you desiring a feature, then consider adding it to our [public feature voting board](https://zenml.io/discussion). Before doing so, do check what is already on there and consider upvoting the features you desire the most.
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/best-practices-upgrading-zenml.md ================ --- description: >- Learn about best practices for upgrading your ZenML server and your code. --- # Best practices for upgrading ZenML While upgrading ZenML is generally a smooth process, there are some best practices that you should follow to ensure a successful upgrade. Based on experiences shared by ZenML users, here are some key strategies and considerations. ## Upgrading your server Follow the tips below while upgrading your server to mitigate data losses, downtime and other issues. ### Data Backups - **Database Backup**: Before upgrading, create a backup of your MySQL database. This allows you to rollback if necessary. - **Automated Backups**: Consider setting up automatic daily backups of your database for added security. Most managed services like AWS RDS, Google Cloud SQL, and Azure Database for MySQL offer automated backup options. ![Screenshot of backups in AWS RDS](../../.gitbook/assets/aws-rds-backups.png) ### Upgrade Strategies - **Staged Upgrade**: For large organizations or critical systems, consider using two ZenML server instances (old and new) and migrating services one by one to the new version. ![Server Migration Step 1](../../.gitbook/assets/server_migration_1.png) ![Server Migration Step 2](../../.gitbook/assets/server_migration_2.png) - **Team Coordination**: If multiple teams share a ZenML server instance, coordinate the upgrade timing to minimize disruption. - **Separate ZenML Servers**: Coordination between teams might be difficult if one team requires new features but the other can't upgrade yet. In such cases, it is recommended to use dedicated ZenML server instances per team or product to allow for more flexible upgrade schedules. {% hint style="info" %} ZenML Pro comes with multi-tenancy which makes it easy for you to have multiple ZenML servers and switch between them. This is useful if you have multiple teams and you want to upgrade them at different times. {% endhint %} ### Minimizing Downtime - **Upgrade Timing**: Plan upgrades during low-activity periods to minimize disruption. - **Avoid Mid-Pipeline Upgrades**: Be cautious of automated upgrades or redeployments that might interrupt long-running pipelines. ## Upgrading your code Sometimes, you might have to upgrade your code to work with a new version of ZenML. This is true especially when you are moving from a really old version to a new major version. The following tips might help, in addition to everything you've learned in this document so far. ### Testing and Compatibility - **Local Testing**: It's a good idea to test it locally first after you upgrade (`pip install zenml --upgrade`) and run some old pipelines to check for compatibility issues between the old and new versions. - **End-to-End Testing**: You can also develop simple end-to-end tests to ensure that the new version works with your pipeline code and your stack. ZenML already has an [extensive test suite](https://github.com/zenml-io/zenml/tree/main/tests) that we use for releases and you can use it as an example. - **Artifact Compatibility**: Be cautious with pickle-based [materializers](../../how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md), as they can be sensitive to changes in Python versions or libraries. Consider using version-agnostic materialization methods for critical artifacts. You can try to load older artifacts with the new version of ZenML to see if they are compatible. Every artifact has an ID which you can use to load it in the following way: ```python from zenml.client import Client artifact = Client().get_artifact_version('YOUR_ARTIFACT_ID') loaded_artifact = artifact.load() ``` ### Dependency Management - **Python Version**: Make sure that the Python version you are using is compatible with the ZenML version you are upgrading to. Check out the [installation guide](../../getting-started/installation.md) to find out which Python version is supported. - **External Dependencies**: Be mindful of external dependencies (e.g. from integrations) that might be incompatible with the new version of ZenML. This could be the case when some older versions are no longer supported or maintained and the ZenML integration is updated to use a newer version. You can find this information in the [release notes](https://github.com/zenml-io/zenml/releases) for the new version of ZenML. ### Handling API Changes While ZenML strives for backward compatibility, be prepared for occasional breaking changes (e.g., [the Pydantic 2 upgrade](https://github.com/zenml-io/zenml/releases/tag/0.60.0)). - **Changelog Review**: Always review the [changelog from new releases](https://github.com/zenml-io/zenml/releases) for new syntax, instructions, or breaking changes. - **Migration Scripts**: Use provided [migration scripts](migration-guide/migration-guide.md) when available to handle database schema changes. By following these best practices, you can minimize risks and ensure a smoother upgrade process for your ZenML server. Remember that each environment is unique, so adapt these guidelines to your specific needs and infrastructure.
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/README.md ================ --- icon: wand-magic-sparkles --- # Manage your ZenML server This section contains guides to help you learn the best practices for upgrading your ZenML server, tips on how to use the ZenML server in production, and how to troubleshoot it. You will also find steps for the recommended way to upgrade your ZenML server and migration guides for moving between certain versions.
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/troubleshoot-your-deployed-server.md ================ --- description: Troubleshooting tips for your ZenML deployment --- # Troubleshoot the deployed server In this document, we will go over some common issues that you might face when deploying ZenML and how to solve them. ## Viewing logs Analyzing logs is a great way to debug issues. Depending on whether you have a Kubernetes (using Helm or `zenml deploy`) or a Docker deployment, you can view the logs in different ways. {% tabs %} {% tab title="Kubernetes" %} If you are using Kubernetes, you can view the logs of the ZenML server using the following method: * Check all pods that are running your ZenML deployment. ```bash kubectl -n get pods ``` * If you see that the pods aren't running, you can use the command below to get the logs for all pods at once. ```bash kubectl -n logs -l app.kubernetes.io/name=zenml ``` Note that the error can either be from the `zenml-db-init` container that connects to the MySQL database or from the `zenml` container that runs the server code. If the get pods command shows that the pod is failing in the `Init` state then use `zenml-db-init` as the container name, otherwise use `zenml`. ```bash kubectl -n logs -l app.kubernetes.io/name=zenml -c ``` {% hint style="info" %} You can also use the `--tail` flag to limit the number of lines to show or the `--follow` flag to follow the logs in real-time. {% endhint %} {% endtab %} {% tab title="Docker" %} If you are using Docker, you can view the logs of the ZenML server using the following method: * If you used the `zenml login --local --docker` CLI command to deploy the Docker ZenML server, you can check the logs with the command: ```shell zenml logs -f ``` * If you used the `docker run` command to manually deploy the Docker ZenML server, you can check the logs with the command: ```shell docker logs zenml -f ``` * If you used the `docker compose` command to manually deploy the Docker ZenML server, you can check the logs with the command: ```shell docker compose -p zenml logs -f ``` {% endtab %} {% endtabs %} ## Fixing database connection problems If you are using a MySQL database, you might face issues connecting to it. The logs from the `zenml-db-init` container should give you a good idea of what the problem is. Here are some common issues and how to fix them: * If you see an error like `ERROR 1045 (28000): Access denied for user using password YES`, it means that the username or password is incorrect. Make sure that the username and password are correctly set for whatever deployment method you are using. * If you see an error like `ERROR 2003 (HY000): Can't connect to MySQL server on ()`, it means that the host is incorrect. Make sure that the host is correctly set for whatever deployment method you are using. You can test the connection and the credentials by running the following command from your machine: ```bash mysql -h -u -p ``` {% hint style="info" %} If you are using a Kubernetes deployment, you can use the `kubectl port-forward` command to forward the MySQL port to your local machine. This will allow you to connect to the database from your machine. {% endhint %} ## Fixing database initialization problems If you’ve migrated from a newer ZenML version to an older version and see errors like `Revision not found` in your `zenml-db-init` logs, one way out is to drop the database and create a new one with the same name. * Log in to your MySQL instance. ```bash mysql -h -u -p ``` * Drop the database for the server. ```sql drop database ; ``` * Create the database with the same name. ```sql create database ; ``` * Restart the Kubernetes pods or the docker container running your server to trigger the database initialization again.
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/upgrade-zenml-server.md ================ --- description: Learn how to upgrade your server to a new version of ZenML for the different deployment options. --- # Upgrade the version of the ZenML server The way to upgrade your ZenML server depends a lot on how you deployed it. However, there are some best practices that apply in all cases. Before you upgrade, check out the [best practices for upgrading ZenML](best-practices-upgrading-zenml.md) guide. In general, upgrade your ZenML server as soon as you can once a new version is released. New versions come with a lot of improvements and fixes from which you can benefit. {% tabs %} {% tab title="Docker" %} To upgrade to a new version with docker, you have to delete the existing container and then run the new version of the `zenml-server` image. {% hint style="danger" %} Check that your data is persisted (either on persistent storage or on an external MySQL instance) before doing this. Optionally also perform a backup before the upgrade. {% endhint %} * Delete the existing ZenML container, for example like this: ```bash # find your container ID docker ps ``` ```bash # stop the container docker stop # remove the container docker rm ``` * Deploy the version of the `zenml-server` image that you want to use. Find all versions [here](https://hub.docker.com/r/zenmldocker/zenml-server/tags). ```bash docker run -it -d -p 8080:8080 --name zenmldocker/zenml-server: ``` {% endtab %} {% tab title="Kubernetes with Helm" %} To upgrade your ZenML server Helm release to a new version, follow the steps below: * Pull the latest version of the Helm chart from the ZenML GitHub repository, or a version of your choice, e.g.: ```bash # If you haven't cloned the ZenML repository yet git clone https://github.com/zenml-io/zenml.git # Optional: checkout an explicit release tag # git checkout 0.21.1 git pull # Switch to the directory that hosts the helm chart cd src/zenml/zen_server/deploy/helm/ ``` * Simply reuse the `custom-values.yaml` file that you used during the previous installation or upgrade. If you don't have it handy, you can extract the values from the ZenML Helm deployment using the following command: ```bash helm -n get values zenml-server > custom-values.yaml ``` * Upgrade the release using your modified values file. Make sure you are in the directory that hosts the helm chart: ```bash helm -n upgrade zenml-server . -f custom-values.yaml ``` {% hint style="info" %} It is not recommended to change the container image tag in the Helm chart to custom values, since every Helm chart version is tested to work only with the default image tag. However, if you know what you're doing you can change the `zenml.image.tag` value in your `custom-values.yaml` file to the desired ZenML version (e.g. `0.32.0`). {% endhint %} {% endtab %} {% endtabs %} {% hint style="warning" %} Downgrading the server to an older version is not supported and can lead to unexpected behavior. {% endhint %} {% hint style="info" %} The version of the Python client that connects to the server should be kept at the same version as the server. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/manage-zenml-server/using-zenml-server-in-prod.md ================ --- description: > Learn about best practices for using ZenML server in production environments. --- # Using ZenML server in production Setting up a ZenML server for testing is a quick process. However, most people have to move beyond so-called 'day zero' operations and in such cases, it helps to learn best practices around setting up your ZenML server in a production-ready way. This guide encapsulates all the tips and tricks we've learned ourselves and from working with people who use ZenML in production environments. Following are some of the best practices we recommend. {% hint style="info" %} If you are using ZenML Pro, you don't have to worry about any of these. We have got you covered! You can sign up for a free trial [here](https://cloud.zenml.io). {% endhint %} ## Autoscaling replicas In production, you often have to run bigger and longer running pipelines that might strain your server's resources. It is a good idea to set up autoscaling for your ZenML server so that you don't have to worry about your pipeline runs getting interrupted or your Dashboard slowing down due to high traffic. How you do it depends greatly on the environment in which you have deployed your ZenML server. Below are some common deployment options and how to set up autoscaling for them. {% tabs %} {% tab title="Kubernetes with Helm" %} If you are using the official [ZenML Helm chart](https://artifacthub.io/packages/helm/zenml/zenml), you can take advantage of the `autoscaling.enabled` flag to enable autoscaling for your ZenML server. For example: ```yaml autoscaling: enabled: true minReplicas: 1 maxReplicas: 10 targetCPUUtilizationPercentage: 80 ``` This will create a horizontal pod autoscaler for your ZenML server that will scale the number of replicas up to 10 and down to 1 based on the CPU utilization of the pods. {% endtab %} {% tab title="ECS" %} For folks using AWS, [ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) is a popular choice for running ZenML server. ECS is a container orchestration service that allows you to run and scale your containers in a managed environment. To scale your ZenML server deployed as a service on ECS, you can follow the steps below: - Go to the ECS console, find you service pertaining to your ZenML server and click on it. - Click on the "Update Service" button. - If you scroll down, you will see the "Service auto scaling - optional" section. - Here you can enable autoscaling and set the minimum and maximum number of tasks to run for your service and also the ECS service metric to use for scaling. ![Image showing autoscaling settings for a service](../../.gitbook/assets/ecs_autoscaling.png) {% endtab %} {% tab title="Cloud Run" %} For folks on GCP, [Cloud Run](https://cloud.google.com/run) is a popular choice for running ZenML server. Cloud Run is a container orchestration service that allows you to run and scale your containers in a managed environment. In Cloud Run, each revision is automatically scaled to the number of instances needed to handle all incoming requests, events, or CPU utilization and by default, when a revision does not receive any traffic, it is scaled in to zero instances. For production use cases, we recommend setting the minimum number of instances to at least 1 so that you have "warm" instances ready to serve incoming requests. To scale your ZenML server deployed on Cloud Run, you can follow the steps below: - Go to the Cloud Run console, find you service pertaining to your ZenML server and click on it. - Click on the "Edit & Deploy new Revision" button. - Scroll down to the "Revision auto-scaling" section. - Here you can set the minimum and maximum number of instances to run for your service. ![Image showing autoscaling settings for a service](../../.gitbook/assets/cloudrun_autoscaling.png) {% endtab %} {% tab title="Docker Compose" %} If you use Docker Compose, you don't get autoscaling out of the box. However, you can scale your service to N number of replicas using the `scale` flag. For example: ```bash docker compose up --scale zenml-server=N ``` This will scale your ZenML server to N replicas. {% endtab %} {% endtabs %} ## High connection pool values One other way to improve the performance of your ZenML server is to increase the number of threads that your server process uses, provided that you have hardware that can support it. You can control this by setting the `zenml.threadPoolSize` value in the ZenML Helm chart values. For example: ```yaml zenml: threadPoolSize: 100 ``` By default, it is set to 40. If you are using any other deployment option, you can set the `ZENML_SERVER_THREAD_POOL_SIZE` environment variable to the desired value. Once this is set, you should also modify the `zenml.database.poolSize` and `zenml.database.maxOverflow` values to ensure that the ZenML server workers do not block on database connections (i.e. the sum of the pool size and max overflow should be greater than or equal to the thread pool size). If you manage your own database, ensure these values are set appropriately. ## Scaling the backing database An important component of the ZenML server deployment is the backing database. When you start scaling your ZenML server instances, you will also need to scale your database to avoid any bottlenecks. We would recommend starting out with a simple (single) database instance and then monitoring it to decide if it needs scaling. Some common metrics to look out for: - CPU Utilization: If the CPU Utilization is consistently above 50%, you may need to scale your database. Some spikes in the utlization are expected but it should not be consistently high. - Freeable Memory: It is natural for the freeable memory to go down with time as your database uses it for caching and buffering but if it drops below 100-200 MB, you may need to scale your database. ## Setting up an ingress/load balancer Exposing your ZenML server to the internet securely and reliably is a must for production use cases. One way to do this is to set up an ingress/load balancer. {% tabs %} {% tab title="Kubernetes with Helm" %} If you are using the official [ZenML Helm chart](https://artifacthub.io/packages/helm/zenml/zenml), you can take advantage of the `zenml.ingress.enabled` flag to enable ingress for your ZenML server. For example: ```yaml zenml: ingress: enabled: true className: "nginx" annotations: # nginx.ingress.kubernetes.io/ssl-redirect: "true" # nginx.ingress.kubernetes.io/rewrite-target: /$1 # kubernetes.io/ingress.class: nginx # kubernetes.io/tls-acme: "true" # cert-manager.io/cluster-issuer: "letsencrypt" ``` This will create an [NGINX ingress](https://github.com/kubernetes/ingress-nginx) for your ZenML service that will create a LoadBalancer on whatever cloud provider you are using. {% endtab %} {% tab title="ECS" %} With ECS, you can use Application Load Balancers to evenly route traffic to your tasks running your ZenML server. Follow the steps in the official [AWS documentation](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-load-balancing.html) to learn how to set this up. {% endtab %} {% tab title="Cloud Run" %} With Cloud Run, you can use Cloud Load Balancing to route traffic to your service. Follow the steps in the official [GCP documentation](https://cloud.google.com/load-balancing/docs/https/setting-up-https-serverless) to learn how to set this up. {% endtab %} {% tab title="Docker Compose" %} If you are using Docker Compose, you can set up an NGINX server as a reverse proxy to route traffic to your ZenML server. Here's a [blog](https://www.docker.com/blog/how-to-use-the-official-nginx-docker-image/) that shows how to do it. {% endtab %} {% endtabs %} ## Monitoring Monitoring your service is crucial to ensure that it is running smoothly and to catch any issues early before they can cause problems. Depending on the deployment option you are using, you can use different tools to monitor your service. {% tabs %} {% tab title="Kubernetes with Helm" %} You can set up Prometheus and Grafana to monitor your ZenML server. We recommend using the `kube-prometheus-stack` [Helm chart from the prometheus-community](https://artifacthub.io/packages/helm/prometheus-community/kube-prometheus-stack) to get started quickly. Once you have deployed the chart, you can find your grafana service by searching for services in the namespace you have deployed the chart in. Port-forward it to your local machine or deploy it through an ingress. You can now use queries like the following to monitor your ZenML server: ``` sum by(namespace) (rate(container_cpu_usage_seconds_total{namespace=~"zenml.*"}[5m])) ``` This query would give you the CPU utilization of your server pods in all namespaces that start with `zenml`. The image below shows how this query would look like in Grafana. ![Image showing CPU utilization of ZenML server pods](../../.gitbook/assets/grafana_dashboard.png) {% endtab %} {% tab title="ECS" %} On ECS, you can utilize the [CloudWatch integration](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cloudwatch-metrics.html) to monitor your ZenML server. In the "Health and metrics" section of your ECS console, you should see metrics pertaining to your ZenML service like CPU utilization and Memory utilization. ![Image showing CPU utilization ECS](../../.gitbook/assets/ecs_cpu_utilization.png) {% endtab %} {% tab title="Cloud Run" %} In Cloud Run, you can utilize the [Cloud Monitoring integration](https://cloud.google.com/run/docs/monitoring) to monitor your ZenML server. The "Metrics" tab in the Cloud Run console will show you metrics like Container CPU utilization, Container memory utilization, and more. ![Image showing metrics in Cloud Run](../../.gitbook/assets/cloudrun_metrics.png) {% endtab %} {% endtabs %} ## Backups The data in your ZenML server is critical as it contains your pipeline runs, stack configurations, and other important information. It is, therefore, recommended to have a backup strategy in place to avoid losing any data. Some common strategies include: - Setting up automated backups with a good retention period (say 30 days). - Periodically exporting the data to an external storage (e.g. S3, GCS, etc.). - Manual backups before upgrading your server to avoid any problems.
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/model-control-plane/associate-a-pipeline-with-a-model.md ================ # Associate a pipeline with a Model The most common use-case for a Model is to associate it with a pipeline.
from zenml import pipeline
from zenml import Model

@pipeline(
    model=Model(
        name="ClassificationModel",  # Give your models unique names
        tags=["MVP", "Tabular"]  # Use tags for future filtering
    )
)
def my_pipeline():
    ...
This will associate this pipeline with the model specified. In case the model already exists, this will create a new version of that model. In case you want to attach the pipeline to an existing model version, specify this as well. ```python from zenml import pipeline from zenml import Model from zenml.enums import ModelStages @pipeline( model=Model( name="ClassificationModel", # Give your models unique names tags=["MVP", "Tabular"], # Use tags for future filtering version=ModelStages.LATEST # Alternatively use a stage: [STAGING, PRODUCTION]] ) ) def my_pipeline(): ... ``` Feel free to also move the Model configuration into your configuration files: ```yaml ... model: name: text_classifier description: A breast cancer classifier tags: ["classifier","sgd"] ... ```
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/model-control-plane/connecting-artifacts-via-a-model.md ================ --- description: Structuring an MLOps project --- # Connecting artifacts via a Model Now that we've learned about managing [artifacts](../../../user-guide/starter-guide/manage-artifacts.md) and [models](../../../user-guide/starter-guide/track-ml-models.md), we can shift our attention again to the thing that brings them together: [Pipelines](../../../user-guide/starter-guide/create-an-ml-pipeline.md). This trifecta together will then inform how we structure our project. {% hint style="info" %} In order to see the recommended repository structure of a ZenML MLOps project, read the [best practices](../../project-setup-and-management/setting-up-a-project-repository/README.md) section. {% endhint %} An MLOps project can often be broken down into many different pipelines. For example: * A `feature engineering` pipeline that prepares raw data into a format ready to get trained. * A `training pipeline` that takes input data from a feature engineering pipeline and trains a models on it. * An `inference pipeline` that runs batch predictions on the trained model and often takes pre-processing from the training pipeline. * A deployment pipeline that deploys a trained model into a production endpoint. The lines between these pipelines can often get blurry: Some use cases call for these pipelines to be merged into one big pipeline. Others go further and break the pipeline down into even smaller chunks. Ultimately, the decision of how to structure your pipelines depends on the use case and requirements of the project. No matter how you design these pipelines, one thing stays consistent: you will often need to transfer or share information (in particular artifacts, models, and metadata) between pipelines. Here are some common patterns that you can use to help facilitate such an exchange: ## Pattern 1: Artifact exchange between pipelines through `Client` Let's say we have a feature engineering pipeline and a training pipeline. The feature engineering pipeline is like a factory, pumping out many different datasets. Only a few of these datasets should be selected to be sent to the training pipeline to train an actual model.

A simple artifact exchange between two pipelines

In this scenario, the [ZenML Client](../../../reference/python-client.md#client-methods) can be used to facilitate such an exchange: ```python from zenml import pipeline from zenml.client import Client @pipeline def feature_engineering_pipeline(): dataset = load_data() # This returns artifacts called "iris_training_dataset" and "iris_testing_dataset" train_data, test_data = prepare_data() @pipeline def training_pipeline(): client = Client() # Fetch by name alone - uses the latest version of this artifact train_data = client.get_artifact_version(name="iris_training_dataset") # For test, we want a particular version test_data = client.get_artifact_version(name="iris_testing_dataset", version="raw_2023") # We can now send these directly into ZenML steps sklearn_classifier = model_trainer(train_data) model_evaluator(model, sklearn_classifier) ``` {% hint style="info" %} Please note, that in the above example, the `train_data` and `test_data` artifacts are not [materialized](../../data-artifact-management/handle-data-artifacts/artifact-versioning.md) in memory in the `@pipeline` function, but rather the `train_data` and `test_data` objects are simply references to where this data is stored in the artifact store. Therefore, one cannot use any logic regarding the nature of this data itself during compilation time (i.e. in the `@pipeline` function). {% endhint %} ## Pattern 2: Artifact exchange between pipelines through a `Model` While passing around artifacts with IDs or names is very useful, it is often desirable to have the ZenML Model be the point of reference instead. For example, let's say we have a training pipeline called `train_and_promote` and an inference pipeline called `do_predictions`. The training pipeline produces many different model artifacts, all of which are collected within a [ZenML Model](../../../user-guide/starter-guide/track-ml-models.md). Each time the `train_and_promote` pipeline runs, it creates a new `iris_classifier`. However, it only promotes the model to `production` if a certain accuracy threshold is met. The promotion can be also be done manually with human intervention, or it can be automated through setting a particular threshold. On the other side, the `do_predictions` pipeline simply picks up the latest promoted model and runs batch inference on it. It need not know of the IDs or names of any of the artifacts produced by the training pipeline's many runs. This way these two pipelines can independently be run, but can rely on each other's output.

A simple artifact exchange between pipelines through the Model Control Plane.

In code, this is very simple. Once the [pipelines are configured to use a particular model](../../../user-guide/starter-guide/track-ml-models.md#configuring-a-model-in-a-pipeline), we can use `get_step_context` to fetch the configured model within a step directly. Assuming there is a `predict` step in the `do_predictions` pipeline, we can fetch the `production` model like so: ```python from zenml import step, get_step_context # IMPORTANT: Cache needs to be disabled to avoid unexpected behavior @step(enable_cache=False) def predict( data: pd.DataFrame, ) -> Annotated[pd.Series, "predictions"]: # model name and version are derived from pipeline context model = get_step_context().model # Fetch the model directly from the model control plane model = model.get_model_artifact("trained_model") # Make predictions predictions = pd.Series(model.predict(data)) return predictions ``` However, this approach has the downside that if the step is cached, then it could lead to unexpected results. You could simply disable the cache in the above step or the corresponding pipeline. However, one other way of achieving this would be to resolve the artifact at the pipeline level: ```python from typing_extensions import Annotated from zenml import get_pipeline_context, pipeline, Model from zenml.enums import ModelStages import pandas as pd from sklearn.base import ClassifierMixin @step def predict( model: ClassifierMixin, data: pd.DataFrame, ) -> Annotated[pd.Series, "predictions"]: predictions = pd.Series(model.predict(data)) return predictions @pipeline( model=Model( name="iris_classifier", # Using the production stage version=ModelStages.PRODUCTION, ), ) def do_predictions(): # model name and version are derived from pipeline context model = get_pipeline_context().model inference_data = load_data() predict( # Here, we load in the `trained_model` from a trainer step model=model.get_model_artifact("trained_model"), data=inference_data, ) if __name__ == "__main__": do_predictions() ``` Ultimately, both approaches are fine. You should decide which one to use based on your own preferences.
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/model-control-plane/delete-a-model.md ================ --- description: Learn how to delete models. --- # Delete a model Deleting a model or a specific model version means removing all links between the Model entity and artifacts + pipeline runs, and will also delete all metadata associated with that Model. ## Deleting all versions of a model {% tabs %} {% tab title="CLI" %} ```shell zenml model delete ``` {% endtab %} {% tab title="Python SDK" %} ```python from zenml.client import Client Client().delete_model() ``` {% endtab %} {% endtabs %} ## Delete a specific version of a model {% tabs %} {% tab title="CLI" %} ```shell zenml model version delete ``` {% endtab %} {% tab title="Python SDK" %} ```python from zenml.client import Client Client().delete_model_version() ``` {% endtab %} {% endtabs %}
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/model-control-plane/linking-model-binaries-data-to-models.md ================ # Linking model binaries/data to Models Artifacts generated during pipeline runs can be linked to models in ZenML. This connecting of artifacts provides lineage tracking and transparency into what data and models are used during training, evaluation, and inference. There are a few ways to link artifacts: ## Configuring the Model at a pipeline level The easiest way is to configure the `model` parameter on the `@pipeline` decorator or `@step` decorator: ```python from zenml import Model, pipeline model = Model( name="my_model", version="1.0.0" ) @pipeline(model=model) def my_pipeline(): ... ``` This will automatically link all artifacts from this pipeline run to the specified model configuration. ## Saving intermediate artifacts It is often handy to save some of your work half-way: steps like epoch-based training can be running slow, and you don't want to lose any checkpoints along the way if an error occurs. You can use the `save_artifact` utility function to save your data assets as ZenML artifacts. Moreover, if your step has the Model context configured in the `@pipeline` or `@step` decorator it will be automatically linked to it, so you can get easy access to it using the Model Control Plane features. ```python from zenml import step, Model from zenml.artifacts.utils import save_artifact import pandas as pd from typing_extensions import Annotated from zenml.artifacts.artifact_config import ArtifactConfig @step(model=Model(name="MyModel", version="1.2.42")) def trainer( trn_dataset: pd.DataFrame, ) -> Annotated[ ClassifierMixin, ArtifactConfig("trained_model") ]: # this configuration will be applied to `model` output """Step running slow training.""" ... for epoch in epochs: checkpoint = model.train(epoch) # this will save each checkpoint in `training_checkpoint` artifact # with distinct version e.g. `1.2.42_0`, `1.2.42_1`, etc. # Checkpoint artifacts will be linked to `MyModel` version `1.2.42` # implicitly. save_artifact( data=checkpoint, name="training_checkpoint", version=f"1.2.42_{epoch}", ) ... return model ``` ## Link artifacts explicitly If you would like to link an artifact to a model not from the step context or even outside a step, you can use the `link_artifact_to_model` function. All you need is ready to link artifact and the configuration of a model. ```python from zenml import step, Model, link_artifact_to_model, save_artifact from zenml.client import Client @step def f_() -> None: # produce new artifact new_artifact = save_artifact(data="Hello, World!", name="manual_artifact") # and link it inside a step link_artifact_to_model( artifact_version_id=new_artifact.id, model=Model(name="MyModel", version="0.0.42"), ) # use existing artifact existing_artifact = Client().get_artifact_version(name_id_or_prefix="existing_artifact") # and link it even outside a step link_artifact_to_model( artifact_version_id=existing_artifact.id, model=Model(name="MyModel", version="0.2.42"), ) ```
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/model-control-plane/load-a-model-in-code.md ================ # Load a model in code There are a few different ways to load a ZenML Model in code: ## Load the active model in a pipeline You can also use the [active model](../../../user-guide/starter-guide/track-ml-models.md) to get the model metadata, or the associated artifacts directly as described in the [starter guide](../../../user-guide/starter-guide/track-ml-models.md): ```python from zenml import step, pipeline, get_step_context, pipeline, Model @pipeline(model=Model(name="my_model")) def my_pipeline(): ... @step def my_step(): # Get model from active step context mv = get_step_context().model # Get metadata print(mv.run_metadata["metadata_key"].value) # Directly fetch an artifact that is attached to the model output = mv.get_artifact("my_dataset", "my_version") output.run_metadata["accuracy"].value ``` ## Load any model via the Client Alternatively, you can use the `Client`: ```python from zenml import step from zenml.client import Client from zenml.enums import ModelStages @step def model_evaluator_step() ... # Get staging model version try: staging_zenml_model = Client().get_model_version( model_name_or_id="", model_version_name_or_number_or_id=ModelStages.STAGING, ) except KeyError: staging_zenml_model = None ... ```
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/model-control-plane/load-artifacts-from-model.md ================ # Load artifacts from Model One of the more common use-cases for a Model is to pass artifacts between pipelines (a pattern we have seen [before](connecting-artifacts-via-a-model.md)). However, when and how to load these artifacts is important to know as well. As an example, let's have a look at a two-pipeline project, where the first pipeline is running training logic and the second runs batch inference leveraging trained model artifact(s): ```python from typing_extensions import Annotated from zenml import get_pipeline_context, pipeline, Model from zenml.enums import ModelStages import pandas as pd from sklearn.base import ClassifierMixin @step def predict( model: ClassifierMixin, data: pd.DataFrame, ) -> Annotated[pd.Series, "predictions"]: predictions = pd.Series(model.predict(data)) return predictions @pipeline( model=Model( name="iris_classifier", # Using the production stage version=ModelStages.PRODUCTION, ), ) def do_predictions(): # model name and version are derived from pipeline context model = get_pipeline_context().model inference_data = load_data() predict( # Here, we load in the `trained_model` from a trainer step model=model.get_model_artifact("trained_model"), data=inference_data, ) if __name__ == "__main__": do_predictions() ``` In the example above we used `get_pipeline_context().model` property to acquire the model context in which the pipeline is running. During pipeline compilation this context will not yet have been evaluated, because `Production` model version is not a stable version name and another model version can become `Production` before it comes to the actual step execution. The same applies to calls like `model.get_model_artifact("trained_model")`; it will get stored in the step configuration for delayed materialization which will only happen during the step run itself. It is also possible to achieve the same using bare `Client` methods reworking the pipeline code as follows: ```python from zenml.client import Client @pipeline def do_predictions(): # model name and version are directly passed into client method model = Client().get_model_version("iris_classifier", ModelStages.PRODUCTION) inference_data = load_data() predict( # Here, we load in the `trained_model` from a trainer step model=model.get_model_artifact("trained_model"), data=inference_data, ) ``` In this case the evaluation of the actual artifact will happen only when the step is actually running.
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/model-control-plane/model-versions.md ================ # Model Versions Each model can have many versions. Model versions are a way for you to track different iterations of your training process, complete with some extra dashboard and API functionality to support the full ML lifecycle. E.g. Based on your business rules during training, you can associate model version with stages and promote them to production. You have an interface that allows you to link these versions with non-technical artifacts and data, e.g. business data, datasets, or even stages in your process and workflow. Model versions are created implicitly as you are running your machine learning training, so you don't have to immediately think about this. If you want more control over versions, our API has you covered, with an option to explicitly name your versions. ## Explicitly name your model version If you want to explicitly name your model version, you can do so by passing in the `version` argument to the `Model` object. If you don't do this, ZenML will automatically generate a version number for you. ```python from zenml import Model, step, pipeline model= Model( name="my_model", version="1.0.5" ) # The step configuration will take precedence over the pipeline @step(model=model) def svc_trainer(...) -> ...: ... # This configures it for all steps within the pipeline @pipeline(model=model) def training_pipeline( ... ): # training happens here ``` Here we are specifically setting the model configuration for a particular step or for the pipeline as a whole. {% hint style="info" %} Please note in the above example if the model version exists, it is automatically associated with the pipeline and becomes active in the pipeline context. Therefore, a user should be careful and intentional as to whether you want to create a new pipeline, or fetch an existing one. See below for an example of fetching a model from an existing version/stage. {% endhint %} ## Use name templates for your model versions If you want to continuously run the same project, but keep track of your model versions using semantical naming, you can rely on templated naming in the `version` and/or `name` argument to the `Model` object. Instead of static model version name from the previous section, templated names will be unique with every new run, but also will be semantically searchable and readable by your team. ```python from zenml import Model, step, pipeline model= Model( name="{team}_my_model", version="experiment_with_phi_3_{date}_{time}" ) # The step configuration will take precedence over the pipeline @step(model=model) def llm_trainer(...) -> ...: ... # This configures it for all steps within the pipeline @pipeline(model=model, substitutions={"team": "Team_A"}) def training_pipeline( ... ): # training happens here ``` Here we are specifically setting the model configuration for a particular step or for the pipeline as a whole. Once you run this pipeline it will produce a model version with a name evaluated at a runtime, like `experiment_with_phi_3_2024_08_30_12_42_53`. Subsequent runs will have the same name of the model and model version, since the substitutions like `time` and `date` are evaluated for the whole pipeline run. We also used a custom substitution via `{team}` placeholder and set it to `Team_A` in the `pipeline` decorator. {% hint style="info" %} The substitutions for the custom placeholders like `team` can be set in: - `@pipeline` decorator, so they are effective for all steps in this pipeline - `pipeline.with_options` function, so they are effective for all steps in this pipeline run - `@step` decorator, so they are effective for this step (this overrides the pipeline settings) - `step.with_options` function, so they are effective for this step run (this overrides the pipeline settings) Standard substitutions always available and consistent in all steps of the pipeline are: - `{date}`: current date, e.g. `2024_11_27` - `{time}`: current time in UTC format, e.g. `11_07_09_326492` {% endhint %} ## Fetching model versions by stage A common pattern is to assign a special `stage` to a model version, i.e. `production`, `staging`, `development` etc. This marks this version especially, and can be used to fetch it using a particular semantic meaning, disconnected from the concrete model version. A model version can be assigned a particular stage in the dashboard or by executing the following command in the CLI: ```shell zenml model version update MODEL_NAME --stage=STAGE ``` These stages can then be passed in as a `version` to fetch the right model version at a later point: ```python from zenml import Model, step, pipeline model= Model( name="my_model", version="production" ) # The step configuration will take precedence over the pipeline @step(model=model) def svc_trainer(...) -> ...: ... # This configures it for all steps within the pipeline @pipeline(model=model) def training_pipeline( ... ): # training happens here ``` ## Autonumbering of versions ZenML automatically numbers your model versions for you. If you don't specify a version number, or if you pass `None` into the `version` argument of the `Model` object, ZenML will automatically generate a version number (or a new version, if you already have a version) for you. For example if we had a model version `really_good_version` for model `my_model` and we wanted to create a new version of this model, we could do so as follows: ```python from zenml import Model, step model = Model( name="my_model", version="even_better_version" ) @step(model=model) def svc_trainer(...) -> ...: ... ``` A new model version will be created and ZenML will track that this is the next in the iteration sequence of the models using the `number` property. If `really_good_version` was the 5th version of `my_model`, then `even_better_version` will be the 6th version of `my_model`. ```python from zenml import Model earlier_version = Model( name="my_model", version="really_good_version" ).number # == 5 updated_version = Model( name="my_model", version="even_better_version" ).number # == 6 ```
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/model-control-plane/promote-a-model.md ================ # Promote a model ## Stages and Promotion Model stages are a way to model the progress that different versions takes through various stages in its lifecycle. A ZenML Model version can be promoted to a different stage through the Dashboard, the ZenML CLI or code. This is a way to signify the progression of your model version through the ML lifecycle and are an extra layer of metadata to identify the state of a particular model version. Possible options for stages are: * `staging`: This version is staged for production. * `production`: This version is running in a production setting. * `latest`: The latest version of the model. This is a virtual stage to retrieve the latest version only - versions cannot be promoted to `latest`. * `archived`: This is archived and no longer relevant. This stage occurs when a model moves out of any other stage. Your own particular business or use case logic will determine which model version you choose to promote, and you can do this in the following ways: ### Promotion via CLI This is probably the least common way that you'll use, but it's still possible and perhaps might be useful for some use cases or within a CI system, for example. You simply use the following CLI subcommand: ```bash zenml model version update iris_logistic_regression --stage=... ``` ### Promotion via Cloud Dashboard This feature is not yet available, but soon you will be able to promote your model versions directly from the ZenML Pro dashboard. ### Promotion via Python SDK This is the most common way that you'll use to promote your models. You can see how you would do this here: ```python from zenml import Model MODEL_NAME = "iris_logistic_regression" from zenml.enums import ModelStages model = Model(name=MODEL_NAME, version="1.2.3") model.set_stage(stage=ModelStages.PRODUCTION) # get latest model and set it as Staging # (if there is current Staging version it will get Archived) latest_model = Model(name=MODEL_NAME, version=ModelStages.LATEST) latest_model.set_stage(stage=ModelStages.STAGING) ``` Within a pipeline context, you would get the model from the step context but the mechanism for setting the stage is the same. ```python from zenml import get_step_context, step, pipeline from zenml.enums import ModelStages @step def promote_to_staging(): model = get_step_context().model model.set_stage(ModelStages.STAGING, force=True) @pipeline( ... ) def train_and_promote_model(): ... promote_to_staging(after=["train_and_evaluate"]) ``` ## Fetching model versions by stage The stage can be used to load the right model version, by passing them in as a `version`: ```python from zenml import Model, step, pipeline model= Model( name="my_model", version="production" ) # The step configuration will take precedence over the pipeline @step(model=model) def svc_trainer(...) -> ...: ... # This configures it for all steps within the pipeline @pipeline(model=model) def training_pipeline( ... ): # training happens here ```
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/model-control-plane/README.md ================ --- icon: tower-control --- # Use the Model Control Plane ![Walkthrough of ZenML Model Control Plane (Dashboard available only on ZenML Pro)](../../../.gitbook/assets/mcp_walkthrough.gif) A `Model` is simply an entity that groups pipelines, artifacts, metadata, and other crucial business data into a unified entity. A ZenML Model is a concept that more broadly encapsulates your ML products business logic. You may even think of a ZenML Model as a "project" or a "workspace" {% hint style="warning" %} Please note that one of the most common artifacts that is associated with a Model in ZenML is the so-called technical model, which is the actually model file/files that holds the weight and parameters of a machine learning training result. However, this is not the only artifact that is relevant; artifacts such as the training data and the predictions this model produces in production are also linked inside a ZenML Model. {% endhint %} Models are first-class citizens in ZenML and as such viewing and using them is unified and centralized in the ZenML API, client as well as on the [ZenML Pro](https://zenml.io/pro) dashboard. A Model captures lineage information and more. Within a Model, different Model versions can be staged. For example, you can rely on your predictions at a specific stage, like `Production`, and decide whether the Model version should be promoted based on your business rules during training. Plus, accessing data from other Models and their versions is just as simple. The Model Control Plane is how you manage your models through this unified interface. It allows you to combine the logic of your pipelines, artifacts and crucial business data along with the actual 'technical model'. To see an end-to-end example, please refer to the [starter guide](../../../user-guide/starter-guide/track-ml-models.md).
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/model-control-plane/register-a-model.md ================ # Registering models Registering models can be done in a number of ways depending on your specific needs. You can explicitly register models using the CLI or the Python SDK, or you can just allow ZenML to implicitly register your models as part of a pipeline run. {% hint style="info" %} If you are using [ZenML Pro](https://cloud.zenml.io/?utm\_source=docs\&utm\_medium=referral\_link\&utm\_campaign=cloud\_promotion\&utm\_content=signup\_link/), you already have access to a dashboard interface that allows you to register models. {% endhint %} ## Explicit CLI registration Registering models using the CLI is as straightforward as the following command: ```bash zenml model register iris_logistic_regression --license=... --description=... ``` You can view some of the options of what can be passed into this command by running `zenml model register --help` but since you are using the CLI outside a pipeline run the arguments you can pass in are limited to non-runtime items. You can also associate tags with models at this point, for example, using the `--tag` option. ## Explicit dashboard registration [ZenML Pro](https://zenml.io/pro) can register their models directly from the cloud dashboard interface.
ZenML Pro Register Model.

Register a model on the [ZenML Pro](https://zenml.io/pro) dashboard

## Explicit Python SDK registration You can register a model using the Python SDK as follows: ```python from zenml import Model from zenml.client import Client Client().create_model( name="iris_logistic_regression", license="Copyright (c) ZenML GmbH 2023", description="Logistic regression model trained on the Iris dataset.", tags=["regression", "sklearn", "iris"], ) ``` ## Implicit registration by ZenML The most common use case for registering models is to do so implicitly as part of a pipeline run. This is done by specifying a `Model` object as part of the `model` argument of the `@pipeline` decorator. As an example, here we have a training pipeline which orchestrates the training of a model object, storing datasets and the model object itself as links within a newly created Model version. This integration is achieved by configuring the pipeline within a Model Context using `Model`. The name is specified, while other fields remain optional for this task. ```python from zenml import pipeline from zenml import Model @pipeline( enable_cache=False, model=Model( name="demo", license="Apache", description="Show case Model Control Plane.", ), ) def train_and_promote_model(): ... ``` Running the training pipeline creates a new model version, all while maintaining a connection to the artifacts.
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/track-metrics-metadata/attach-metadata-to-a-model.md ================ --- description: Learn how to attach metadata to a model. --- # Attach metadata to a model ZenML allows you to log metadata for models, which provides additional context that goes beyond individual artifact details. Model metadata can represent high-level insights, such as evaluation results, deployment information, or customer-specific details, making it easier to manage and interpret the model's usage and performance across different versions. ## Logging Metadata for Models To log metadata for a model, use the `log_metadata` function. This function lets you attach key-value metadata to a model, which can include metrics and other JSON-serializable values, such as custom ZenML types like `Uri`, `Path`, and `StorageSize`. Here's an example of logging metadata for a model: ```python from typing import Annotated import pandas as pd from sklearn.base import ClassifierMixin from sklearn.ensemble import RandomForestClassifier from zenml import step, log_metadata, ArtifactConfig, get_step_context @step def train_model(dataset: pd.DataFrame) -> Annotated[ ClassifierMixin, ArtifactConfig(name="sklearn_classifier") ]: """Train a model and log model metadata.""" classifier = RandomForestClassifier().fit(dataset) accuracy, precision, recall = ... log_metadata( metadata={ "evaluation_metrics": { "accuracy": accuracy, "precision": precision, "recall": recall } }, infer_model=True, ) return classifier ``` In this example, the metadata is associated with the model rather than the specific classifier artifact. This is particularly useful when the metadata reflects an aggregation or summary of various steps and artifacts in the pipeline. ### Selecting Models with `log_metadata` When using `log_metadata`, ZenML provides flexible options of attaching metadata to model versions: 1. **Using `infer_model`**: If used within a step, ZenML will use the step context to infer the model it is using and attach the metadata to it. 2. **Model Name and Version Provided**: If both a model name and version are provided, ZenML will use these to identify and attach metadata to the specific model version. 3. **Model Version ID Provided**: If a model version ID is directly provided, ZenML will use it to fetch and attach the metadata to that specific model version. ## Fetching logged metadata Once metadata has been attached to a model, it can be retrieved for inspection or analysis using the ZenML Client. ```python from zenml.client import Client client = Client() model = client.get_model_version("my_model", "my_version") print(model.run_metadata["metadata_key"]) ``` {% hint style="info" %} When you are fetching metadata using a specific key, the returned value will always reflect the latest entry. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/track-metrics-metadata/attach-metadata-to-a-run.md ================ --- description: Learn how to attach metadata to a run. --- # Attach Metadata to a Run In ZenML, you can log metadata directly to a pipeline run, either during or after execution, using the `log_metadata` function. This function allows you to attach a dictionary of key-value pairs as metadata to a pipeline run, with values that can be any JSON-serializable data type, including ZenML custom types like `Uri`, `Path`, `DType`, and `StorageSize`. ## Logging Metadata Within a Run If you are logging metadata from within a step that’s part of a pipeline run, calling `log_metadata` will attach the specified metadata to the current pipeline run where the metadata key will have the `step_name::metadata_key` pattern. This allows you to use the same metadata key from different steps while the run's still executing. ```python from typing import Annotated import pandas as pd from sklearn.base import ClassifierMixin from sklearn.ensemble import RandomForestClassifier from zenml import step, log_metadata, ArtifactConfig @step def train_model(dataset: pd.DataFrame) -> Annotated[ ClassifierMixin, ArtifactConfig(name="sklearn_classifier", is_model_artifact=True) ]: """Train a model and log run-level metadata.""" classifier = RandomForestClassifier().fit(dataset) accuracy, precision, recall = ... # Log metadata at the run level log_metadata( metadata={ "run_metrics": { "accuracy": accuracy, "precision": precision, "recall": recall } } ) return classifier ``` ## Manually Logging Metadata to a Pipeline Run You can also attach metadata to a specific pipeline run without needing a step, using identifiers like the run ID. This is useful when logging information or metrics that were calculated post-execution. ```python from zenml import log_metadata log_metadata( metadata={"post_run_info": {"some_metric": 5.0}}, run_id_name_or_prefix="run_id_name_or_prefix" ) ``` ## Fetching Logged Metadata Once metadata has been logged in a pipeline run, you can retrieve it using the ZenML Client: ```python from zenml.client import Client client = Client() run = client.get_pipeline_run("run_id_name_or_prefix") print(run.run_metadata["metadata_key"]) ``` {% hint style="info" %} When you are fetching metadata using a specific key, the returned value will always reflect the latest entry. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/track-metrics-metadata/attach-metadata-to-a-step.md ================ --- description: Learn how to attach metadata to a step. --- # Attach metadata to a step In ZenML, you can log metadata for a specific step during or after its execution by using the `log_metadata` function. This function allows you to attach a dictionary of key-value pairs as metadata to a step. The metadata can be any JSON-serializable value, including custom classes such as `Uri`, `Path`, `DType`, and `StorageSize`. ## Logging Metadata Within a Step If called within a step, `log_metadata` automatically attaches the metadata to the currently executing step and its associated pipeline run. This is ideal for logging metrics or information that becomes available during the step execution. ```python from typing import Annotated import pandas as pd from sklearn.base import ClassifierMixin from sklearn.ensemble import RandomForestClassifier from zenml import step, log_metadata, ArtifactConfig @step def train_model(dataset: pd.DataFrame) -> Annotated[ ClassifierMixin, ArtifactConfig(name="sklearn_classifier") ]: """Train a model and log evaluation metrics.""" classifier = RandomForestClassifier().fit(dataset) accuracy, precision, recall = ... # Log metadata at the step level log_metadata( metadata={ "evaluation_metrics": { "accuracy": accuracy, "precision": precision, "recall": recall } } ) return classifier ``` {% hint style="info" %} If you run a pipeline where the step execution is cached, the cached step run will copy the metadata that was created in the original step execution. (If there is any metadata that was generated manually after the execution of the original step, these entries will not be included in this process.) {% endhint %} ## Manually Logging Metadata a Step Run You can also log metadata for a specific step after execution, using identifiers to specify the pipeline, step, and run. This approach is useful when you want to log metadata post-execution. ```python from zenml import log_metadata log_metadata( metadata={ "additional_info": {"a_number": 3} }, step_name="step_name", run_id_name_or_prefix="run_id_name_or_prefix" ) # or log_metadata( metadata={ "additional_info": {"a_number": 3} }, step_id="step_id", ) ``` ## Fetching logged metadata Once metadata has been logged in a step, we can easily fetch the metadata with the ZenML Client: ```python from zenml.client import Client client = Client() step = client.get_pipeline_run("pipeline_id").steps["step_name"] print(step.run_metadata["metadata_key"]) ``` {% hint style="info" %} When you are fetching metadata using a specific key, the returned value will always reflect the latest entry. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/track-metrics-metadata/attach-metadata-to-an-artifact.md ================ --- description: Learn how to attach metadata to an artifact. --- # Attach metadata to an artifact ![Metadata in the dashboard](../../../.gitbook/assets/metadata-in-dashboard.png) In ZenML, metadata enhances artifacts by adding context and important details, such as size, structure, or performance metrics. This metadata is accessible in the ZenML dashboard, making it easier to inspect, compare, and track artifacts across pipeline runs. ## Logging Metadata for Artifacts Artifacts in ZenML are outputs of steps within a pipeline, such as datasets, models, or evaluation results. Associating metadata with artifacts can help users understand the nature and characteristics of these outputs. To log metadata for an artifact, use the `log_metadata` function, specifying the artifact name, version, or ID. The metadata can be any JSON-serializable value, including ZenML custom types like `Uri`, `Path`, `DType`, and `StorageSize`. Find out more about these different types [here](../../model-management-metrics/track-metrics-metadata/logging-metadata.md). Here's an example of logging metadata for an artifact: ```python import pandas as pd from zenml import step, log_metadata from zenml.metadata.metadata_types import StorageSize @step def process_data_step(dataframe: pd.DataFrame) -> pd.DataFrame: """Process a dataframe and log metadata about the result.""" processed_dataframe = ... # Log metadata about the processed dataframe log_metadata( metadata={ "row_count": len(processed_dataframe), "columns": list(processed_dataframe.columns), "storage_size": StorageSize( processed_dataframe.memory_usage().sum()) }, infer_artifact=True, ) return processed_dataframe ``` ### Selecting the artifact to log the metadata to When using `log_metadata` with an artifact name, ZenML provides flexible options to attach metadata to the correct artifact: 1. **Using `infer_artifact`**: If used within a step, ZenML will use the step context to infer the outputs artifacts of the step. If the step has only one output, this artifact will be selected. However, if you additionally provide an `artifact_name`, ZenML will search for this name in the output space of the step (useful for step with multiple outputs). 2. **Name and Version Provided**: If both an artifact name and version are provided, ZenML will use these to identify and attach metadata to the specific artifact version. 3. **Artifact Version ID Provided**: If an artifact version ID is provided directly, ZenML will use it to fetch and attach the metadata to that specific artifact version. ## Fetching logged metadata Once metadata has been logged in an artifact, or [step](../track-metrics-metadata/attach-metadata-to-a-model.md), we can easily fetch the metadata with the ZenML Client: ```python from zenml.client import Client client = Client() artifact = client.get_artifact_version("my_artifact", "my_version") print(artifact.run_metadata["metadata_key"]) ``` {% hint style="info" %} When you are fetching metadata using a specific key, the returned value will always reflect the latest entry. {% endhint %} ## Grouping Metadata in the Dashboard When logging metadata passing a dictionary of dictionaries in the `metadata` parameter will group the metadata into cards in the ZenML dashboard. This feature helps organize metadata into logical sections, making it easier to visualize and understand. Here's an example of grouping metadata into cards: ```python from zenml import log_metadata from zenml.metadata.metadata_types import StorageSize log_metadata( metadata={ "model_metrics": { "accuracy": 0.95, "precision": 0.92, "recall": 0.90 }, "data_details": { "dataset_size": StorageSize(1500000), "feature_columns": ["age", "income", "score"] } }, artifact_name="my_artifact", artifact_version="version", ) ``` In the ZenML dashboard, `model_metrics` and `data_details` would appear as separate cards, each containing their respective key-value pairs.
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/track-metrics-metadata/fetch-metadata-within-pipeline.md ================ --- description: How to fetch metadata during pipeline composition. --- # Fetch metadata during pipeline composition ### Pipeline configuration using the `PipelineContext` To find information about the pipeline configuration during pipeline composition, you can use the `zenml.get_pipeline_context()` function to access the `PipelineContext` of your pipeline: ```python from zenml import get_pipeline_context, pipeline ... @pipeline( extra={ "complex_parameter": [ ("sklearn.tree", "DecisionTreeClassifier"), ("sklearn.ensemble", "RandomForestClassifier"), ] } ) def my_pipeline(): context = get_pipeline_context() after = [] search_steps_prefix = "hp_tuning_search_" for i, model_search_configuration in enumerate( context.extra["complex_parameter"] ): step_name = f"{search_steps_prefix}{i}" cross_validation( model_package=model_search_configuration[0], model_class=model_search_configuration[1], id=step_name ) after.append(step_name) select_best_model( search_steps_prefix=search_steps_prefix, after=after, ) ``` {% hint style="info" %} See the [SDK Docs](https://sdkdocs.zenml.io/latest/core_code_docs/core-new/#zenml.pipelines.pipeline_context.PipelineContext) for more information on which attributes and methods the `PipelineContext` provides. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/track-metrics-metadata/fetch-metadata-within-steps.md ================ --- description: Accessing meta information in real-time within your pipeline. --- # Fetch metadata within steps ## Using the `StepContext` To find information about the pipeline or step that is currently running, you can use the `zenml.get_step_context()` function to access the `StepContext` of your step: ```python from zenml import step, get_step_context @step def my_step(): step_context = get_step_context() pipeline_name = step_context.pipeline.name run_name = step_context.pipeline_run.name step_name = step_context.step_run.name ``` Furthermore, you can also use the `StepContext` to find out where the outputs of your current step will be stored and which [Materializer](../../data-artifact-management/handle-data-artifacts/handle-custom-data-types.md) class will be used to save them: ```python from zenml import step, get_step_context @step def my_step(): step_context = get_step_context() # Get the URI where the output will be saved. uri = step_context.get_output_artifact_uri() # Get the materializer that will be used to save the output. materializer = step_context.get_output_materializer() ``` {% hint style="info" %} See the [SDK Docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-new/#zenml.steps.step\_context.StepContext) for more information on which attributes and methods the `StepContext` provides. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/track-metrics-metadata/grouping-metadata.md ================ --- description: Learn how to group key-value pairs in the dashboard. --- # Grouping Metadata in the Dashboard ![Metadata in the dashboard](../../../.gitbook/assets/metadata-in-dashboard.png) When logging metadata passing a dictionary of dictionaries in the `metadata` parameter will group the metadata into cards in the ZenML dashboard. This feature helps organize metadata into logical sections, making it easier to visualize and understand. Here's an example of grouping metadata into cards: ```python from zenml import log_metadata from zenml.metadata.metadata_types import StorageSize log_metadata( metadata={ "model_metrics": { "accuracy": 0.95, "precision": 0.92, "recall": 0.90 }, "data_details": { "dataset_size": StorageSize(1500000), "feature_columns": ["age", "income", "score"] } }, artifact_name="my_artifact", artifact_version="my_artifact_version", ) ``` In the ZenML dashboard, "model_metrics" and "data_details" would appear as separate cards, each containing their respective key-value pairs.
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/track-metrics-metadata/logging-metadata.md ================ --- description: Tracking your metadata. --- # Special Metadata Types ZenML supports several special metadata types to capture specific kinds of information. Here are examples of how to use the special types `Uri`, `Path`, `DType`, and `StorageSize`: ```python from zenml import log_metadata from zenml.metadata.metadata_types import StorageSize, DType, Uri, Path log_metadata( metadata={ "dataset_source": Uri("gs://my-bucket/datasets/source.csv"), "preprocessing_script": Path("/scripts/preprocess.py"), "column_types": { "age": DType("int"), "income": DType("float"), "score": DType("int") }, "processed_data_size": StorageSize(2500000) }, ) ``` In this example: * `Uri` is used to indicate a dataset source URI. * `Path` is used to specify the filesystem path to a preprocessing script. * `DType` is used to describe the data types of specific columns. * `StorageSize` is used to indicate the size of the processed data in bytes. These special types help standardize the format of metadata and ensure that it is logged in a consistent and interpretable manner.
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/track-metrics-metadata/README.md ================ --- icon: ufo-beam description: Tracking and comparing metrics and metadata --- # Track metrics and metadata ZenML provides a unified way to log and manage metrics and metadata through the `log_metadata` function. This versatile function allows you to log metadata across various entities like models, artifacts, steps, and runs through a single interface. Additionally, you can adjust if you want to automatically log the same metadata for related entities. ## Logging Metadata ### The most basic use-case You can use the `log_metadata` function within a step: ```python from zenml import step, log_metadata @step def my_step() -> ...: log_metadata(metadata={"accuracy": 0.91}) ... ``` This will log the `accuracy` for the step, its pipeline run, and if provided its model version. ### A real-world example Here's a more comprehensive example showing how to log various types of metadata in a machine learning pipeline: ```python from zenml import step, pipeline, log_metadata @step def process_engine_metrics() -> float: # does some machine learning things # Log operational metrics log_metadata( metadata={ "engine_temperature": 3650, # Kelvin "fuel_consumption_rate": 245, # kg/s "thrust_efficiency": 0.92, } ) return 0.92 @step def analyze_flight_telemetry(efficiency: float) -> None: # does some more machine learning things # Log performance metrics log_metadata( metadata={ "altitude": 220000, # meters "velocity": 7800, # m/s "fuel_remaining": 2150, # kg "mission_success_prob": 0.9985, } ) @pipeline def telemetry_pipeline(): efficiency = process_engine_metrics() analyze_flight_telemetry(efficiency) ``` This data can be visualized and compared in the ZenML Pro dashboard. The illustrations below show the data from this example in the [ZenML Pro](https://www.zenml.io/pro) dashboard using the Experiment Comparison tool. {% hint style="warning" %} This feature is currently in Alpha Preview. We encourage you to share feedback about your use cases and requirements through our Slack community. {% endhint %} ## Visualizing and Comparing Metadata (Pro) Once you've logged metadata in your pipelines, you can use ZenML's Experiment Comparison tool to analyze and compare metrics across different runs. This feature is available in the [ZenML Pro](https://www.zenml.io/pro) dashboard. [![Experiment Comparison Introduction Video](../../../../book/.gitbook/assets/experiment_comparison_video.png)](https://www.loom.com/share/693b2d829600492da7cd429766aeba6a?sid=7182e55b-31e9-4b38-a3be-07c989dbea32) ### Comparison Views The Experiment Comparison tool offers two complementary views for analyzing your pipeline metadata: 1. **Table View**: Compare metadata across runs with automatic change tracking ![Table View](../../../../book/.gitbook/assets/table-view.png) 2. **Parallel Coordinates Plot**: Visualize relationships between different metrics ![Parallel Coordinates](../../../../book/.gitbook/assets/coordinates-view.png) The tool lets you compare up to 20 pipeline runs simultaneously and supports any numerical metadata (`float` or `int`) that you've logged in your pipelines. ### Additional use-cases The `log_metadata` function supports various use-cases by allowing you to specify the target entity (e.g., model, artifact, step, or run) with flexible parameters. You can learn more about these use-cases in the following pages: - [Log metadata to a step](attach-metadata-to-a-step.md) - [Log metadata to a run](attach-metadata-to-a-run.md) - [Log metadata to an artifact](attach-metadata-to-an-artifact.md) - [Log metadata to a model](attach-metadata-to-a-model.md) {% hint style="warning" %} The older methods for logging metadata to specific entities, such as `log_model_metadata`, `log_artifact_metadata`, and `log_step_metadata`, are now deprecated. It is recommended to use `log_metadata` for all future implementations. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/model-management-metrics/README.md ================ --- icon: chart-tree-map --- # Model Management and Metrics This section covers all aspects of managing models and tracking metrics in ZenML. ================ File: docs/book/how-to/pipeline-development/build-pipelines/access-secrets-in-a-step.md ================ # Access secrets in a step ## Fetching secret values in a step ZenML secrets are groupings of **key-value pairs** which are securely stored in the ZenML secrets store. Additionally, a secret always has a **name** that allows you to fetch or reference them in your pipelines and stacks. In order to learn more about how to configure and create secrets, please refer to the [platform guide on secrets](../../../getting-started/deploying-zenml/secret-management.md). You can access secrets directly from within your steps through the ZenML `Client` API. This allows you to use your secrets for querying APIs from within your step without hard-coding your access keys: ```python from zenml import step from zenml.client import Client from somewhere import authenticate_to_some_api @step def secret_loader() -> None: """Load the example secret from the server.""" # Fetch the secret from ZenML. secret = Client().get_secret("") # `secret.secret_values` will contain a dictionary with all key-value # pairs within your secret. authenticate_to_some_api( username=secret.secret_values["username"], password=secret.secret_values["password"], ) ... ``` *** ### See Also:
Learn how to create and manage secrets interact-with-secrets.md
Find out more about the secrets backend in ZenML secret-management.md
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/compose-pipelines.md ================ --- description: Reuse steps between pipelines. --- # Compose pipelines Sometimes it can be useful to extract some common functionality into separate functions in order to avoid code duplication. To facilitate this, ZenML allows you to compose your pipelines: ```python from zenml import pipeline @pipeline def data_loading_pipeline(mode: str): if mode == "train": data = training_data_loader_step() else: data = test_data_loader_step() processed_data = preprocessing_step(data) return processed_data @pipeline def training_pipeline(): training_data = data_loading_pipeline(mode="train") model = training_step(data=training_data) test_data = data_loading_pipeline(mode="test") evaluation_step(model=model, data=test_data) ``` {% hint style="info" %} Here we are calling one pipeline from within another pipeline, so functionally the `data_loading_pipeline` is functioning as a step within the `training_pipeline`, i.e. the steps of the former are added to the latter. Only the parent pipeline will be visible in the dashboard. In order to actually trigger a pipeline from another, see [here](../../trigger-pipelines/use-templates-python.md#advanced-usage-run-a-template-from-another-pipeline) {% endhint %}
Learn more about orchestrators hereorchestrators.md
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/configuring-a-pipeline-at-runtime.md ================ --- description: Configuring a pipeline at runtime. --- # Runtime configuration of a pipeline run It is often the case that there is a need to run a pipeline with a different configuration. In this case, you should in most cases use the [`pipeline.with_options`](../../pipeline-development/use-configuration-files/README.md) method. You can do this: 1. Either by explicitly configuring options like `with_options(steps="trainer": {"parameters": {"param1": 1}})` 2. Or by passing a YAML file using `with_options(config_file="path_to_yaml_file")`. You can learn more about these options [here](../../pipeline-development/use-configuration-files/README.md). However, there is one exception: if you would like to trigger a pipeline from the client or another pipeline, you would need to pass the `PipelineRunConfiguration` object. Learn more about this [here](../../trigger-pipelines/use-templates-python.md#advanced-usage-run-a-template-from-another-pipeline).
Using config files../../pipeline-development/use-configuration-files/README.md
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/control-caching-behavior.md ================ --- description: >- By default steps in ZenML pipelines are cached whenever code and parameters stay unchanged. --- # Control caching behavior ```python @step(enable_cache=True) # set cache behavior at step level def load_data(parameter: int) -> dict: ... @step(enable_cache=False) # settings at step level override pipeline level def train_model(data: dict) -> None: ... @pipeline(enable_cache=True) # set cache behavior at step level def simple_ml_pipeline(parameter: int): ... ``` {% hint style="info" %} Caching only happens when code and parameters stay the same. {% endhint %} Like many other step and pipeline settings, you can also change this afterward: ```python # Same as passing it in the step decorator my_step.configure(enable_cache=...) # Same as passing it in the pipeline decorator my_pipeline.configure(enable_cache=...) ``` ***
Find out here how to configure this in a YAML fileuse-configuration-files
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/control-execution-order-of-steps.md ================ # Control execution order of steps By default, ZenML uses the data flowing between steps of your pipeline to determine the order in which steps get executed. The following example shows a pipeline in which `step_3` depends on the outputs of `step_1` and `step_2`. This means that ZenML can execute both `step_1` and `step_2` in parallel but needs to wait until both are finished before `step_3` can be started. ```python from zenml import pipeline @pipeline def example_pipeline(): step_1_output = step_1() step_2_output = step_2() step_3(step_1_output, step_2_output) ``` If you have additional constraints on the order in which steps get executed, you can specify non-data dependencies by passing the invocation IDs of steps that should run before your step like this: `my_step(after="other_step")`. If you want to define multiple upstream steps, you can also pass a list for the `after` argument when calling your step: `my_step(after=["other_step", "other_step_2"])`. {% hint style="info" %} Check out the [documentation here](using-a-custom-step-invocation-id.md) to learn about the invocation ID and how to use a custom one for your steps. {% endhint %} ```python from zenml import pipeline @pipeline def example_pipeline(): step_1_output = step_1(after="step_2") step_2_output = step_2() step_3(step_1_output, step_2_output) ``` This pipeline is similar to the one explained above, but this time ZenML will make sure to only start `step_1` after `step_2` has finished.
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/delete-a-pipeline.md ================ --- description: Learn how to delete pipelines. --- # Delete a pipeline In order to delete a pipeline, you can either use the CLI or the Python SDK: {% tabs %} {% tab title="CLI" %} ```shell zenml pipeline delete ``` {% endtab %} {% tab title="Python SDK" %} ```python from zenml.client import Client Client().delete_pipeline() ``` {% endtab %} {% endtabs %} {% hint style="info" %} Deleting a pipeline does not automatically delete any of its associated runs or artifacts. {% endhint %} If you want to delete multiple pipelines at once, you might find the Python SDK preferable. If you have pipelines with the same prefix, you will need to pass in the `id` of each pipeline separately so ZenML is able to identify them. In this case, you could use a script like the following: ```python from zenml.client import Client client = Client() # Get the list of pipelines that start with "test_pipeline" # use a large size to ensure we get all of them pipelines_list = client.list_pipelines(name="startswith:test_pipeline", size=100) target_pipeline_ids = [p.id for p in pipelines_list.items] print(f"Found {len(target_pipeline_ids)} pipelines to delete") confirmation = input("Do you really want to delete these pipelines? (y/n): ").lower() if confirmation == 'y': print(f"Deleting {len(target_pipeline_ids)} pipelines") for pid in target_pipeline_ids: client.delete_pipeline(pid) print("Deletion complete") else: print("Deletion cancelled") ``` ## Delete a pipeline run To delete a pipeline run, you can use the following CLI command or the client: {% tabs %} {% tab title="CLI" %} ```shell zenml pipeline runs delete ``` {% endtab %} {% tab title="Python SDK" %} ```python from zenml.client import Client Client().delete_pipeline_run() ``` {% endtab %} {% endtabs %}
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/fan-in-fan-out.md ================ --- description: Running steps in parallel. --- # Fan-in and Fan-out Patterns The fan-out/fan-in pattern is a common pipeline architecture where a single step splits into multiple parallel operations (fan-out) and then consolidates the results back into a single step (fan-in). This pattern is particularly useful for parallel processing, distributed workloads, or when you need to process data through different transformations and then aggregate the results. For example, you might want to process different chunks of data in parallel and then aggregate the results: ```python from zenml import step, get_step_context, pipeline from zenml.client import Client @step def load_step() -> str: return "Hello from ZenML!" @step def process_step(input_data: str) -> str: return input_data @step def combine_step(step_prefix: str, output_name: str) -> None: run_name = get_step_context().pipeline_run.name run = Client().get_pipeline_run(run_name) # Fetch all results from parallel processing steps processed_results = {} for step_name, step_info in run.steps.items(): if step_name.startswith(step_prefix): output = step_info.outputs[output_name][0] processed_results[step_info.name] = output.load() # Combine all results print(",".join([f"{k}: {v}" for k, v in processed_results.items()])) @pipeline(enable_cache=False) def fan_out_fan_in_pipeline(parallel_count: int) -> None: # Initial step (source) input_data = load_step() # Fan out: Process data in parallel branches after = [] for i in range(parallel_count): _ = process_step(input_data, id=f"process_{i}") after.append(f"process_{i}") # Fan in: Combine results from all parallel branches combine_step(step_prefix="process_", output_name="output", after=after) fan_out_fan_in_pipeline(parallel_count=8) ``` The fan-out pattern allows for parallel processing and better resource utilization, while the fan-in pattern enables aggregation and consolidation of results. This is particularly useful for: - Parallel data processing - Distributed model training - Ensemble methods - Batch processing - Data validation across multiple sources - [Hyperparameter tuning](./hyper-parameter-tuning.md) Note that when implementing the fan-in step, you'll need to use the ZenML Client to query the results from previous parallel steps, as shown in the example above, and you can't pass in the result directly. {% hint style="warning" %} The fan-in, fan-out method has the following limitations: 1. Steps run sequentially rather than in parallel if the underlying orchestrator does not support parallel step runs (e.g. with the local orchestrator) 2. The number of steps need to be known ahead-of-time, and ZenML does not yet support the ability to dynamically create steps on the fly. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/fetching-pipelines.md ================ --- description: Inspecting a finished pipeline run and its outputs. --- # Fetching pipelines Once a pipeline run has been completed, we can access the corresponding information in code, which enables the following: * Loading artifacts like models or datasets saved by previous runs * Accessing metadata or configurations of previous runs * Programmatically inspecting the lineage of pipeline runs and their artifacts The hierarchy of pipelines, runs, steps, and artifacts is as follows: ```mermaid flowchart LR pipelines -->|1:N| runs runs -->|1:N| steps steps -->|1:N| artifacts ``` As you can see from the diagram, there are many layers of 1-to-N relationships. Let us investigate how to traverse this hierarchy level by level: ## Pipelines ### Get a pipeline via the client After you have run a pipeline at least once, you can also fetch the pipeline via the [`Client.get_pipeline()`](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-client/#zenml.client.Client.get\_pipeline) method. ```python from zenml.client import Client pipeline_model = Client().get_pipeline("first_pipeline") ``` {% hint style="info" %} Check out the [ZenML Client Documentation](../../../reference/python-client.md) for more information on the `Client` class and its purpose. {% endhint %} ### Discover and list all pipelines If you're not sure which pipeline you need to fetch, you can find a list of all registered pipelines in the ZenML dashboard, or list them programmatically either via the Client or the CLI. {% tabs %} {% tab title="Python" %} You can use the [`Client.list_pipelines()`](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-client/#zenml.client.Client.list\_pipelines) method to get a list of all pipelines registered in ZenML: ```python from zenml.client import Client pipelines = Client().list_pipelines() ``` {% endtab %} {% tab title="CLI" %} Alternatively, you can also list pipelines with the following CLI command: ```shell zenml pipeline list ``` {% endtab %} {% endtabs %} ## Runs Each pipeline can be executed many times, resulting in several **Runs**. ### Get all runs of a pipeline You can get a list of all runs of a pipeline using the `runs` property of the pipeline: ```python runs = pipeline_model.runs ``` The result will be a list of the most recent runs of this pipeline, ordered from newest to oldest. {% hint style="info" %} Alternatively, you can also use the `pipeline_model.get_runs()` method which allows you to specify detailed parameters for filtering or pagination. See the [ZenML SDK Docs](../../../reference/python-client.md#list-of-resources) for more information. {% endhint %} ### Get the last run of a pipeline To access the most recent run of a pipeline, you can either use the `last_run` property or access it through the `runs` list: ``` last_run = pipeline_model.last_run # OR: pipeline_model.runs[0] ``` {% hint style="info" %} If your most recent runs have failed, and you want to find the last run that has succeeded, you can use the `last_successful_run` property instead. {% endhint %} ### Get the latest run from a pipeline Calling a pipeline executes it and then returns the response of the freshly executed run. ```python run = training_pipeline() ``` {% hint style="warning" %} The run that you get back is the model stored in the ZenML database at the point of the method call. This means the pipeline run is still initializing and no steps have been run. To get the latest state can get a refreshed version from the client: ```python from zenml.client import Client Client().get_pipeline_run(run.id) # to get a refreshed version ``` {% endhint %} ### Get a run via the client If you already know the exact run that you want to fetch (e.g., from looking at the dashboard), you can use the [`Client.get_pipeline_run()`](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-client/#zenml.client.Client.get\_pipeline\_run) method to fetch the run directly without having to query the pipeline first: ```python from zenml.client import Client pipeline_run = Client().get_pipeline_run("first_pipeline-2023_06_20-16_20_13_274466") ``` {% hint style="info" %} Similar to pipelines, you can query runs by either ID, name, or name prefix, and you can also discover runs through the Client or CLI via the [`Client.list_pipeline_runs()`](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-client/#zenml.client.Client.list\_pipeline\_runs) or `zenml pipeline runs list` commands. {% endhint %} ### Run information Each run has a collection of useful information which can help you reproduce your runs. In the following, you can find a list of some of the most useful pipeline run information, but there is much more available. See the [`PipelineRunResponse`](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-models/#zenml.models.v2.core.pipeline\_run.PipelineRunResponse) definition for a comprehensive list. #### Status The status of a pipeline run. There are five possible states: initialized, failed, completed, running, and cached. ```python status = run.status ``` #### Configuration The `pipeline_configuration` is an object that contains all configurations of the pipeline and pipeline run, including the [pipeline-level settings](../../../user-guide/production-guide/configure-pipeline.md), which we will learn more about later: ```python pipeline_config = run.config pipeline_settings = run.config.settings ``` #### Component-Specific metadata Depending on the stack components you use, you might have additional component-specific metadata associated with your run, such as the URL to the UI of a remote orchestrator. You can access this component-specific metadata via the `run_metadata` attribute: ````python run_metadata = run.run_metadata # The following only works for runs on certain remote orchestrators orchestrator_url = run_metadata["orchestrator_url"].value ## Steps Within a given pipeline run you can now further zoom in on individual steps using the `steps` attribute: ```python # get all steps of a pipeline for a given run steps = run.steps # get a specific step by its invocation ID step = run.steps["first_step"] ```` {% hint style="info" %} If you're only calling each step once inside your pipeline, the **invocation ID** will be the same as the name of your step. For more complex pipelines, check out [this page](../../pipeline-development/build-pipelines/using-a-custom-step-invocation-id.md) to learn more about the invocation ID. {% endhint %} ### Inspect pipeline runs with our VS Code extension ![GIF of our VS code extension, showing some of the uses of the sidebar](../../../.gitbook/assets/zenml-extension-shortened.gif) If you are using [our VS Code extension](https://marketplace.visualstudio.com/items?itemName=ZenML.zenml-vscode), you can easily view your pipeline runs by opening the sidebar (click on the ZenML icon). You can then click on any particular pipeline run to see its status and some other metadata. If you want to delete a run, you can also do so from the same sidebar view. ### Step information Similar to the run, you can use the `step` object to access a variety of useful information: * The parameters used to run the step via `step.config.parameters`, * The step-level settings via `step.config.settings`, * Component-specific step metadata, such as the URL of an experiment tracker or model deployer, via `step.run_metadata` See the [`StepRunResponse`](https://github.com/zenml-io/zenml/blob/main/src/zenml/models/v2/core/step_run.py) definition for a comprehensive list of available information. ## Artifacts Each step of a pipeline run can have multiple output and input artifacts that we can inspect via the `outputs` and `inputs` properties. To inspect the output artifacts of a step, you can use the `outputs` attribute, which is a dictionary that can be indexed using the name of an output. Alternatively, if your step only has a single output, you can use the `output` property as a shortcut directly: ```python # The outputs of a step are accessible by name output = step.outputs["output_name"] # If there is only one output, you can use the `.output` property instead output = step.output # use the `.load()` method to load the artifact into memory my_pytorch_model = output.load() ``` Similarly, you can use the `inputs` and `input` properties to get the input artifacts of a step instead. {% hint style="info" %} Check out [this page](../../../user-guide/starter-guide/manage-artifacts.md#giving-names-to-your-artifacts) to see what the output names of your steps are and how to customize them. {% endhint %} Note that the output of a step corresponds to a specific artifact version. ### Fetching artifacts directly If you'd like to fetch an artifact or an artifact version directly, it is easy to do so with the `Client`: ```python from zenml.client import Client # Get artifact artifact = Client().get_artifact('iris_dataset') artifact.versions # Contains all the versions of the artifact output = artifact.versions['2022'] # Get version name "2022" # Get artifact version directly: # Using version name: output = Client().get_artifact_version('iris_dataset', '2022') # Using UUID output = Client().get_artifact_version('f429f94c-fb15-43b5-961d-dbea287507c5') loaded_artifact = output.load() ``` ### Artifact information Regardless of how one fetches it, each artifact contains a lot of general information about the artifact as well as datatype-specific metadata and visualizations. #### Metadata All output artifacts saved through ZenML will automatically have certain datatype-specific metadata saved with them. NumPy Arrays, for instance, always have their storage size, `shape`, `dtype`, and some statistical properties saved with them. You can access such metadata via the `run_metadata` attribute of an output, e.g.: ```python output_metadata = output.run_metadata storage_size_in_bytes = output_metadata["storage_size"].value ``` We will talk more about metadata [in the next section](../../../user-guide/starter-guide/manage-artifacts.md#logging-metadata-for-an-artifact). #### Visualizations ZenML automatically saves visualizations for many common data types. Using the `visualize()` method you can programmatically show these visualizations in Jupyter notebooks: ```python output.visualize() ``` ![output.visualize() Output](../../../.gitbook/assets/artifact\_visualization\_evidently.png) {% hint style="info" %} If you're not in a Jupyter notebook, you can simply view the visualizations in the ZenML dashboard by running `zenml login --local` and clicking on the respective artifact in the pipeline run DAG instead. Check out the [artifact visualization page](../../../how-to/data-artifact-management/visualize-artifacts/README.md) to learn more about how to build and view artifact visualizations in ZenML! {% endhint %} ## Fetching information during run execution While most of this document has focused on fetching objects after a pipeline run has been completed, the same logic can also be used within the context of a running pipeline. This is often desirable in cases where a pipeline is running continuously over time and decisions have to be made according to older runs. For example, this is how we can fetch the last pipeline run of the same pipeline from within a ZenML step: ```python from zenml import get_step_context from zenml.client import Client @step def my_step(): # Get the name of the current pipeline run current_run_name = get_step_context().pipeline_run.name # Fetch the current pipeline run current_run = Client().get_pipeline_run(current_run_name) # Fetch the previous run of the same pipeline previous_run = current_run.pipeline.runs[1] # index 0 is the current run ``` {% hint style="info" %} As shown in the example, we can get additional information about the current run using the `StepContext`, which is explained in more detail in the [advanced docs](../../model-management-metrics/track-metrics-metadata/fetch-metadata-within-steps.md). {% endhint %} ## Code example This section combines all the code from this section into one simple script that you can use to see the concepts discussed above:
Code Example of this Section Putting it all together, this is how we can load the model trained by the `svc_trainer` step of our example pipeline from the previous sections: ```python from typing_extensions import Tuple, Annotated import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.base import ClassifierMixin from sklearn.svm import SVC from zenml import pipeline, step from zenml.client import Client @step def training_data_loader() -> Tuple[ Annotated[pd.DataFrame, "X_train"], Annotated[pd.DataFrame, "X_test"], Annotated[pd.Series, "y_train"], Annotated[pd.Series, "y_test"], ]: """Load the iris dataset as tuple of Pandas DataFrame / Series.""" iris = load_iris(as_frame=True) X_train, X_test, y_train, y_test = train_test_split( iris.data, iris.target, test_size=0.2, shuffle=True, random_state=42 ) return X_train, X_test, y_train, y_test @step def svc_trainer( X_train: pd.DataFrame, y_train: pd.Series, gamma: float = 0.001, ) -> Tuple[ Annotated[ClassifierMixin, "trained_model"], Annotated[float, "training_acc"], ]: """Train a sklearn SVC classifier and log to MLflow.""" model = SVC(gamma=gamma) model.fit(X_train.to_numpy(), y_train.to_numpy()) train_acc = model.score(X_train.to_numpy(), y_train.to_numpy()) print(f"Train accuracy: {train_acc}") return model, train_acc @pipeline def training_pipeline(gamma: float = 0.002): X_train, X_test, y_train, y_test = training_data_loader() svc_trainer(gamma=gamma, X_train=X_train, y_train=y_train) if __name__ == "__main__": # You can run the pipeline and get the run object directly last_run = training_pipeline() print(last_run.id) # You can also use the class directly with the `model` object last_run = training_pipeline.model.last_run print(last_run.id) # OR you can fetch it after execution is finished: pipeline = Client().get_pipeline("training_pipeline") last_run = pipeline.last_run print(last_run.id) # You can now fetch the model trainer_step = last_run.steps["svc_trainer"] model = trainer_step.outputs["trained_model"].load() ```
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/get-past-pipeline-step-runs.md ================ # Get past pipeline/step runs In order to get past pipeline/step runs, you can use the `get_pipeline` method in combination with the `last_run` property or just index into the runs:
from zenml.client import Client

client = Client()

# Retrieve a pipeline by its name
p = client.get_pipeline("mlflow_train_deploy_pipeline")

# Get the latest run of this pipeline
latest_run = p.last_run
# Alternatively you can also access runs by index or name
first_run = p[0]

ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/hyper-parameter-tuning.md ================ --- description: Running a hyperparameter tuning trial with ZenML. --- # Hyperparameter tuning A basic iteration through a number of hyperparameters can be achieved with ZenML by using a simple pipeline. The following example showcases an implementation of a basic grid search (across a single dimension) that would allow for a different learning rate to be used across the same `train_step`. Once that step has been run for all the different learning rates, the `selection_step` finds which hyperparameters gave the best results or performance. It utilizes the [fan-in, fan-out method of building a pipeline.](./fan-in-fan-out.md) ```python from typing import Annotated from sklearn.base import ClassifierMixin from zenml import step, pipeline, get_step_context from zenml.client import Client model_output_name = "my_model" @step def train_step( learning_rate: float ) -> Annotated[ClassifierMixin, model_output_name]: return ... # Train a model with the learning rate and return it here. @step def selection_step(step_prefix: str, output_name: str) -> None: run_name = get_step_context().pipeline_run.name run = Client().get_pipeline_run(run_name) trained_models_by_lr = {} for step_name, step_info in run.steps.items(): if step_name.startswith(step_prefix): model = step_info.outputs[output_name][0].load() lr = step_info.config.parameters["learning_rate"] trained_models_by_lr[lr] = model for lr, model in trained_models_by_lr.items(): ... # Evaluate the models to find the best one @pipeline def my_pipeline(step_count: int) -> None: after = [] for i in range(step_count): train_step(learning_rate=i * 0.0001, id=f"train_step_{i}") after.append(f"train_step_{i}") selection_step( step_prefix="train_step_", output_name=model_output_name, after=after ) my_pipeline(step_count=4) ``` {% hint style="warning" %} The main challenge of this implementation is that it is currently not possible to pass a variable number of artifacts into a step programmatically, so the `selection_step` needs to query all artifacts produced by the previous steps via the ZenML Client instead. {% endhint %} {% hint style="info" %} You can also see this in action with the [E2E example](https://github.com/zenml-io/zenml/tree/main/examples/e2e). In the `steps/hp_tuning` folder, you will find two step files, that can be used as a starting point for building your own hyperparameter search tailored specifically to your use case: * [`hp_tuning_single_search(...)`](https://github.com/zenml-io/zenml/blob/main/examples/e2e/steps/hp_tuning/hp_tuning_single_search.py) is performing a randomized search for the best model hyperparameters in a configured space. * [`hp_tuning_select_best_model(...)`](https://github.com/zenml-io/zenml/blob/main/examples/e2e/steps/hp_tuning/hp_tuning_select_best_model.py) is searching for the best hyperparameters, looping other results of previous random searches to find the best model according to a defined metric. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/name-your-pipeline-runs.md ================ # Name your pipeline runs In the output logs of a pipeline run you will see the name of the run: ```bash Pipeline run training_pipeline-2023_05_24-12_41_04_576473 has finished in 3.742s. ``` This name is automatically generated based on the current date and time. To change the name for a run, pass `run_name` as a parameter to the `with_options()` method: ```python training_pipeline = training_pipeline.with_options( run_name="custom_pipeline_run_name" ) training_pipeline() ``` Pipeline run names must be unique, so if you plan to run your pipelines multiple times or run them on a schedule, make sure to either compute the run name dynamically or include one of the placeholders that ZenML will replace. {% hint style="info" %} The substitutions for the custom placeholders like `experiment_name` can be set in: - `@pipeline` decorator, so they are effective for all steps in this pipeline - `pipeline.with_options` function, so they are effective for all steps in this pipeline run Standard substitutions always available and consistent in all steps of the pipeline are: - `{date}`: current date, e.g. `2024_11_27` - `{time}`: current time in UTC format, e.g. `11_07_09_326492` {% endhint %} ```python training_pipeline = training_pipeline.with_options( run_name="custom_pipeline_run_name_{experiment_name}_{date}_{time}" ) training_pipeline() ```
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/README.md ================ --- icon: flask description: >- Building pipelines is as simple as adding the @step and @pipeline decorators to your code. --- # Build a pipeline ```python from zenml import pipeline, step @step # Just add this decorator def load_data() -> dict: training_data = [[1, 2], [3, 4], [5, 6]] labels = [0, 1, 0] return {'features': training_data, 'labels': labels} @step def train_model(data: dict) -> None: total_features = sum(map(sum, data['features'])) total_labels = sum(data['labels']) # Train some model here print(f"Trained model using {len(data['features'])} data points. " f"Feature sum is {total_features}, label sum is {total_labels}") @pipeline # This function combines steps together def simple_ml_pipeline(): dataset = load_data() train_model(dataset) ``` You can now run this pipeline by simply calling the function: ```python simple_ml_pipeline() ``` When this pipeline is executed, the run of the pipeline gets logged to the ZenML dashboard where you can now go to look at its DAG and all the associated metadata. To access the dashboard you need to have a ZenML server either running locally or remotely. See our documentation on this [here](../../../getting-started/deploying-zenml/README.md).

DAG representation in the ZenML Dashboard.

Check below for more advanced ways to build and interact with your pipeline.
Configure pipeline/step parametersuse-pipeline-step-parameters.md
Name and annotate step outputsstep-output-typing-and-annotation.md
Control caching behaviorcontrol-caching-behavior.md
Customize the step invocation idsusing-a-custom-step-invocation-id.md
Name your pipeline runsname-your-pipeline-runs.md
Use failure/success hooksuse-failure-success-hooks.md
Hyperparameter tuninghyper-parameter-tuning.md
Attach metadata to a stepattach-metadata-to-a-step.md
Fetch metadata within stepsfetch-metadata-within-steps.md
Fetch metadata during pipeline compositionfetch-metadata-within-pipeline.md
Enable or disable logs storingenable-or-disable-logs-storing.md
Special Metadata Typeslogging-metadata.md
Access secrets in a stepaccess-secrets-in-a-step.md
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/reference-environment-variables-in-configurations.md ================ # Reference environment variables in configurations To make your configurations in code as well as in configuration files more flexible, ZenML allows you to reference environment variables by using the following placeholder syntax in your configuration: `${ENV_VARIABLE_NAME}` ## In-code ```python from zenml import step @step(extra={"value_from_environment": "${ENV_VAR}"}) def my_step() -> None: ... ``` # In a configuration file ```yaml extra: value_from_environment: ${ENV_VAR} combined_value: prefix_${ENV_VAR}_suffix ```
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/retry-steps.md ================ --- description: Automatically configure your steps to retry if they fail. --- # Allow step retry in case of failure ZenML provides a built-in retry mechanism that allows you to configure automatic retries for your steps in case of failures. This can be useful when dealing with intermittent issues or transient errors. A common pattern when trying to run a step on GPU-backed hardware is that the provider will not have enough resources available, so you can set ZenML to handle the retries until the resources free up. You can configure three parameters for step retries: * **max_retries:** The maximum number of times the step should be retried in case of failure. * **delay:** The initial delay in **seconds** before the first retry attempt. * **backoff:** The factor by which the delay should be multiplied after each retry attempt. ## Using the @step decorator: You can specify the retry configuration directly in the definition of your step as follows: ```python from zenml.config.retry_config import StepRetryConfig @step( retry=StepRetryConfig( max_retries=3, delay=10, backoff=2 ) ) def my_step() -> None: raise Exception("This is a test exception") steps: my_step: retry: max_retries: 3 delay: 10 backoff: 2 ``` {% hint style="info" %} Note that infinite retries are not supported at the moment. If you set `max_retries` to a very large value or do not specify it at all, ZenML will still enforce an internal maximum number of retries to prevent infinite loops. We recommend setting a reasonable `max_retries` value based on your use case and the expected frequency of transient failures. {% endhint %} *** ### See Also:
Failure/Success Hooksuse-failure-success-hooks.md
Configure pipelines./use-configuration-files/how-to-use-config.md
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/run-an-individual-step.md ================ # Run an individual step on your stack If you want to run just an individual step on your stack, you can simply call the step as you would with a normal Python function. ZenML will internally create a pipeline with just your step and run it on the active stack. {% hint style="info" %} The pipeline run that will happen to execute your step will be `unlisted`, which means it will not be associated with any pipeline. You can still see it in the "Runs" tab of the dashboard. {% endhint %} ```python from zenml import step import pandas as pd from sklearn.base import ClassifierMixin from sklearn.svm import SVC # Configure the step to use a step operator. If you're not using # a step operator, you can remove this and the step will run on # your orchestrator instead. @step(step_operator="") def svc_trainer( X_train: pd.DataFrame, y_train: pd.Series, gamma: float = 0.001, ) -> Tuple[ Annotated[ClassifierMixin, "trained_model"], Annotated[float, "training_acc"], ]: """Train a sklearn SVC classifier.""" model = SVC(gamma=gamma) model.fit(X_train.to_numpy(), y_train.to_numpy()) train_acc = model.score(X_train.to_numpy(), y_train.to_numpy()) print(f"Train accuracy: {train_acc}") return model, train_acc X_train = pd.DataFrame(...) y_train = pd.Series(...) # Call the step directly. This will internally create a # pipeline with just this step, which will be executed on # the active stack. model, train_acc = svc_trainer(X_train=X_train, y_train=y_train) ``` ## Run the underlying step function directly If you instead want to run your step function without ZenML getting involved, you can use the `entrypoint(...)` method of a step: ```python X_train = pd.DataFrame(...) y_train = pd.Series(...) model, train_acc = svc_trainer.entrypoint(X_train=X_train, y_train=y_train) ``` {% hint style="info" %} If you want to make this the default behavior when calling a step, you can set the `ZENML_RUN_SINGLE_STEPS_WITHOUT_STACK` environment variable to `True`. Once you do that, calling `svc_trainer(...)` will simply call the underlying function and not use your ZenML stack. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/run-pipelines-asynchronously.md ================ --- description: The best way to trigger a pipeline run so that it runs in the background --- # Run pipelines asynchronously By default your pipelines will run synchronously. This means your terminal will follow along the logs as the pipeline is being built/runs. This behavior can be changed in multiple ways. Either the orchestrator can be configured to always run asynchronously by setting `synchronous=False`. The other option is to temporarily set this at the pipeline configuration level during runtime. ```python from zenml import pipeline @pipeline(settings = {"orchestrator": {"synchronous": False}}) def my_pipeline(): ... ``` or in a yaml config file: ```yaml settings: orchestrator.: synchronous: false ``` ***
Learn more about orchestrators hereorchestrators.md
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/schedule-a-pipeline.md ================ --- description: Learn how to set, pause and stop a schedule for pipelines. --- # Schedule a pipeline {% hint style="info" %} Schedules don't work for all orchestrators. Here is a list of all supported orchestrators. {% endhint %} | Orchestrator | Scheduling Support | |----------------------------------------------------------------------------------|--------------------| | [AirflowOrchestrator](../../../component-guide/orchestrators/airflow.md) | ✅ | | [AzureMLOrchestrator](../../../component-guide/orchestrators/azureml.md) | ✅ | | [DatabricksOrchestrator](../../../component-guide/orchestrators/databricks.md) | ✅ | | [HyperAIOrchestrator](../../../component-guide/orchestrators/hyperai.md) | ✅ | | [KubeflowOrchestrator](../../../component-guide/orchestrators/kubeflow.md) | ✅ | | [KubernetesOrchestrator](../../../component-guide/orchestrators/kubernetes.md) | ✅ | | [LocalOrchestrator](../../../component-guide/orchestrators/local.md) | ⛔️ | | [LocalDockerOrchestrator](../../../component-guide/orchestrators/local-docker.md) | ⛔️ | | [SagemakerOrchestrator](../../../component-guide/orchestrators/sagemaker.md) | ⛔️ | | [SkypilotAWSOrchestrator](../../../component-guide/orchestrators/skypilot-vm.md) | ⛔️ | | [SkypilotAzureOrchestrator](../../../component-guide/orchestrators/skypilot-vm.md) | ⛔️ | | [SkypilotGCPOrchestrator](../../../component-guide/orchestrators/skypilot-vm.md) | ⛔️ | | [SkypilotLambdaOrchestrator](../../../component-guide/orchestrators/skypilot-vm.md) | ⛔️ | | [TektonOrchestrator](../../../component-guide/orchestrators/tekton.md) | ⛔️ | | [VertexOrchestrator](../../../component-guide/orchestrators/vertex.md) | ✅ | ### Set a schedule ```python from zenml.config.schedule import Schedule from zenml import pipeline from datetime import datetime @pipeline() def my_pipeline(...): ... # Use cron expressions schedule = Schedule(cron_expression="5 14 * * 3") # or alternatively use human-readable notations schedule = Schedule(start_time=datetime.now(), interval_second=1800) my_pipeline = my_pipeline.with_options(schedule=schedule) my_pipeline() ``` {% hint style="info" %} Check out our [SDK docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-config/#zenml.config.schedule.Schedule) to learn more about the different scheduling options. {% endhint %} ### Pause/Stop a schedule The way pipelines are scheduled depends on the orchestrator you are using. For example, if you are using Kubeflow, you can use the Kubeflow UI to stop or pause a scheduled run. However, the exact steps for stopping or pausing a scheduled run may vary depending on the orchestrator you are using. We recommend consulting the documentation for your orchestrator to learn the current method for stopping or pausing a scheduled run. {% hint style="warning" %} Note that ZenML only gets involved to schedule a run, but maintaining the lifecycle of the schedule (as explained above) is the responsibility of the user. If you run a pipeline containing a schedule two times, two scheduled pipelines (with different/unique names) will be created. {% endhint %} *** ### See Also:
Schedules rely on remote orchestrators, learn about those here orchestrators.md
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/step-output-typing-and-annotation.md ================ --- description: >- Step outputs are stored in your artifact store. Annotate and name them to make more explicit. --- # Step output typing and annotation ## Type annotations Your functions will work as ZenML steps even if you don't provide any type annotations for their inputs and outputs. However, adding type annotations to your step functions gives you lots of additional benefits: * **Type validation of your step inputs**: ZenML makes sure that your step functions receive an object of the correct type from the upstream steps in your pipeline. * **Better serialization**: Without type annotations, ZenML uses [Cloudpickle](https://github.com/cloudpipe/cloudpickle) to serialize your step outputs. When provided with type annotations, ZenML can choose a [materializer](../../../getting-started/core-concepts.md#materializers) that is best suited for the output. In case none of the builtin materializers work, you can even [write a custom materializer](../../data-artifact-management/handle-data-artifacts/handle-custom-data-types.md). {% hint style="warning" %} ZenML provides a built-in [CloudpickleMaterializer](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-materializers/#zenml.materializers.cloudpickle\_materializer.CloudpickleMaterializer) that can handle any object by saving it with [cloudpickle](https://github.com/cloudpipe/cloudpickle). However, this is not production-ready because the resulting artifacts cannot be loaded when running with a different Python version. In such cases, you should consider building a [custom Materializer](../handle-data-artifacts/handle-custom-data-types.md#custom-materializers) to save your objects in a more robust and efficient format. Moreover, using the `CloudpickleMaterializer` could allow users to upload of any kind of object. This could be exploited to upload a malicious file, which could execute arbitrary code on the vulnerable system. {% endhint %} ```python from typing import Tuple from zenml import step @step def square_root(number: int) -> float: return number ** 0.5 # To define a step with multiple outputs, use a `Tuple` type annotation @step def divide(a: int, b: int) -> Tuple[int, int]: return a // b, a % b ``` If you want to make sure you get all the benefits of type annotating your steps, you can set the environment variable `ZENML_ENFORCE_TYPE_ANNOTATIONS` to `True`. ZenML will then raise an exception in case one of the steps you're trying to run is missing a type annotation. ### Tuple vs multiple outputs It is impossible for ZenML to detect whether you want your step to have a single output artifact of type `Tuple` or multiple output artifacts just by looking at the type annotation. We use the following convention to differentiate between the two: When the `return` statement is followed by a tuple literal (e.g. `return 1, 2` or `return (value_1, value_2)`) we treat it as a step with multiple outputs. All other cases are treated as a step with a single output of type `Tuple`. ```python from zenml import step from typing_extensions import Annotated from typing import Tuple # Single output artifact @step def my_step() -> Tuple[int, int]: output_value = (0, 1) return output_value # Single output artifact with variable length @step def my_step(condition) -> Tuple[int, ...]: if condition: output_value = (0, 1) else: output_value = (0, 1, 2) return output_value # Single output artifact using the `Annotated` annotation @step def my_step() -> Annotated[Tuple[int, ...], "my_output"]: return 0, 1 # Multiple output artifacts @step def my_step() -> Tuple[int, int]: return 0, 1 # Not allowed: Variable length tuple annotation when using # multiple output artifacts @step def my_step() -> Tuple[int, ...]: return 0, 1 ``` ## Step output names By default, ZenML uses the output name `output` for single output steps and `output_0, output_1, ...` for steps with multiple outputs. These output names are used to display your outputs in the dashboard and [fetch them after your pipeline is finished](fetching-pipelines.md). If you want to use custom output names for your steps, use the `Annotated` type annotation: ```python from typing_extensions import Annotated # or `from typing import Annotated on Python 3.9+ from typing import Tuple from zenml import step @step def square_root(number: int) -> Annotated[float, "custom_output_name"]: return number ** 0.5 @step def divide(a: int, b: int) -> Tuple[ Annotated[int, "quotient"], Annotated[int, "remainder"] ]: return a // b, a % b ``` {% hint style="info" %} If you do not give your outputs custom names, the created artifacts will be named `{pipeline_name}::{step_name}::output` or `{pipeline_name}::{step_name}::output_{i}` in the dashboard. See the [documentation on artifact versioning and configuration](../../../user-guide/starter-guide/manage-artifacts.md) for more information. {% endhint %} *** ### See Also:
Learn more about output annotation here return-multiple-outputs-from-a-step.md
For custom data types you should check these docs out handle-custom-data-types.md
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/tag-your-pipeline-runs.md ================ # Tag your pipeline runs You can specify tags for your pipeline runs in the following places - in the configuration file: ```yaml # config.yaml tags: - tag_in_config_file ``` - in code on the `@pipeline` decorator or using the `with_options` method: ```python @pipeline(tags=["tag_on_decorator"]) def my_pipeline(): ... my_pipeline = my_pipeline.with_options(tags=["tag_on_with_options"]) ``` If you now run this pipeline, tags from all these places will be merged and applied to the pipeline run.
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/use-failure-success-hooks.md ================ --- description: Running failure and success hooks after step execution. --- # Use failure/success hooks Hooks are a way to perform an action after a step has completed execution. They can be useful in a variety of scenarios, such as sending notifications, logging, or cleaning up resources after a step has been completed. A hook executes right after step execution, within the same environment as the step, therefore it has access to all the dependencies that a step has. Currently, there are two sorts of hooks that can be defined: `on_failure` and `on_success` . * `on_failure`: This hook triggers in the event of a step failing. * `on_success`: This hook triggers in the event of a step succeeding. Here is a short demo for hooks in ZenML: {% embed url="https://www.youtube.com/watch?v=KUW2G3EsqF8" %} Failure and Success Hooks in ZenML Short Demo {% endembed %} ## Defining hooks A hook can be defined as a callback function, and must be accessible within the repository where the pipeline and steps are located. In case of failure hooks, you can optionally add a `BaseException` argument to the hook, allowing you to access the concrete Exception that caused your step to fail: ```python from zenml import step def on_failure(exception: BaseException): print(f"Step failed: {str(exception)}") def on_success(): print("Step succeeded!") @step(on_failure=on_failure) def my_failing_step() -> int: """Returns an integer.""" raise ValueError("Error") @step(on_success=on_success) def my_successful_step() -> int: """Returns an integer.""" return 1 ``` In this example, we define two hooks: `on_failure` and `on_success`, which print a message when the step fails or succeeds, respectively. We then use these hooks with two steps, `my_failing_step` and `my_successful_step`. When `my_failing_step` is executed, it raises a `ValueError`, which triggers the `on_failure` hook. Similarly, when `my_successful_step` is executed, it returns an integer successfully, which triggers the on\_success hook. A step can also be specified as a local user-defined function path (of the form `mymodule.myfile.my_function`). This is particularly useful when defining the hooks via a [YAML Config](../../pipeline-development/use-configuration-files/). ## Defining hooks on a pipeline level In some cases, there is a need to define a hook on all steps of a given pipeline. Rather than having to define it on all steps individually, you can also specify any hook on the pipeline level. ```python @pipeline(on_failure=on_failure, on_success=on_success) def my_pipeline(...): ... ``` {% hint style="info" %} Note, that **step-level** defined hooks take **precedence** over **pipeline-level** defined hooks. {% endhint %}
See it in action with the E2E example _To set up the local environment used below, follow the recommendations from the_ [_Project templates_](../../../how-to/project-setup-and-management/collaborate-with-team/project-templates/README.md)_._ In [`steps/alerts/notify_on.py`](../../../../examples/e2e/steps/alerts/notify_on.py), you will find a step to notify the user about success and a function used to notify the user about step failure using the [Alerter](../../../component-guide/alerters/alerters.md) from the active stack. We use `@step` for success notification to only notify the user about a fully successful pipeline run and not about every successful step. In [`pipelines/training.py`](../../../../examples/e2e/pipelines/training.py), you can find the usage of a notification step and a function. We will attach a `notify_on_failure` function directly to the pipeline definition like this: ```python from zenml import pipeline @pipeline( ... on_failure=notify_on_failure, ... ) ``` At the very end of the training pipeline, we will execute the `notify_on_success` step, but only after all other steps have finished - we control it with `after` statement as follows: ```python ... last_step_name = "promote_metric_compare_promoter" notify_on_success(after=[last_step_name]) ... ```
## Accessing step information inside a hook Similar as for regular ZenML steps, you can use the [StepContext](../../model-management-metrics/track-metrics-metadata/fetch-metadata-within-steps.md) to access information about the current pipeline run or step inside your hook function: ```python from zenml import step, get_step_context def on_failure(exception: BaseException): context = get_step_context() print(context.step_run.name) # Output will be `my_step` print(context.step_run.config.parameters) # Print parameters of the step print(type(exception)) # Of type value error print("Step failed!") @step(on_failure=on_failure) def my_step(some_parameter: int = 1) raise ValueError("My exception") ```
See it in action with the E2E example _To set up the local environment used below, follow the recommendations from the_ [_Project templates_](../../../how-to/project-setup-and-management/collaborate-with-team/project-templates/README.md)_._ In [`steps/alerts/notify_on.py`](../../../../examples/e2e/steps/alerts/notify_on.py), you will find a step to notify the user about success and a function used to notify the user about step failure using the [Alerter](../../../component-guide/alerters/alerters.md) from the active stack. We use `@step` for success notification to only notify the user about a fully successful pipeline run and not about every successful step. Inside the helper function `build_message()`, you will find an example on how developers can work with [StepContext](../../model-management-metrics/track-metrics-metadata/fetch-metadata-within-steps.md) to form a proper notification: ```python from zenml import get_step_context def build_message(status: str) -> str: """Builds a message to post. Args: status: Status to be set in text. Returns: str: Prepared message. """ step_context = get_step_context() run_url = get_run_url(step_context.pipeline_run) return ( f"Pipeline `{step_context.pipeline.name}` [{str(step_context.pipeline.id)}] {status}!\n" f"Run `{step_context.pipeline_run.name}` [{str(step_context.pipeline_run.id)}]\n" f"URL: {run_url}" ) @step(enable_cache=False) def notify_on_success() -> None: """Notifies user on pipeline success.""" step_context = get_step_context() if alerter and step_context.pipeline_run.config.extra["notify_on_success"]: alerter.post(message=build_message(status="succeeded")) ```
## Linking to the `Alerter` Stack component A common use case is to use the [Alerter](../../../component-guide/alerters/alerters.md) component inside the failure or success hooks to notify relevant people. It is quite easy to do this: ```python from zenml import get_step_context from zenml.client import Client def on_failure(): step_name = get_step_context().step_run.name Client().active_stack.alerter.post(f"{step_name} just failed!") ``` ZenML provides standard failure and success hooks that use the alerter you have configured in your stack. Here's an example of how to use them in your pipelines: ```python from zenml.hooks import alerter_success_hook, alerter_failure_hook @step(on_failure=alerter_failure_hook, on_success=alerter_success_hook) def my_step(...): ... ```
See it in action with the E2E example _To set up the local environment used below, follow the recommendations from the_ [_Project templates_](../../../how-to/project-setup-and-management/collaborate-with-team/project-templates/README.md)_._ In [`steps/alerts/notify_on.py`](../../../../examples/e2e/steps/alerts/notify_on.py), you will find a step to notify the user about success and a function used to notify the user about step failure using the [Alerter](../../../component-guide/alerters/alerters.md) from the active stack. We use `@step` for success notification to only notify the user about a fully successful pipeline run and not about every successful step. Inside this code file, you can find how developers can work with Al component to send notification messages across configured channels: ```python from zenml.client import Client from zenml import get_step_context alerter = Client().active_stack.alerter def notify_on_failure() -> None: """Notifies user on step failure. Used in Hook.""" step_context = get_step_context() if alerter and step_context.pipeline_run.config.extra["notify_on_failure"]: alerter.post(message=build_message(status="failed")) ``` If the Al component is not present in Stack we suppress notification, but you can also dump it to the log as Error using: ```python from zenml.client import Client from zenml.logger import get_logger from zenml import get_step_context logger = get_logger(__name__) alerter = Client().active_stack.alerter def notify_on_failure() -> None: """Notifies user on step failure. Used in Hook.""" step_context = get_step_context() if step_context.pipeline_run.config.extra["notify_on_failure"]: if alerter: alerter.post(message=build_message(status="failed")) else: logger.error(message=build_message(status="failed")) ```
## Using the OpenAI ChatGPT failure hook The OpenAI ChatGPT failure hook is a hook that uses the OpenAI integration to generate a possible fix for whatever exception caused the step to fail. It is quite easy to use. (You will need [a valid OpenAI API key](https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key) that has correctly set up billing for this.) {% hint style="warning" %} Note that using this integration will incur charges on your OpenAI account. {% endhint %} First, ensure that you have the OpenAI integration installed and have stored your API key within a ZenML secret: ```shell zenml integration install openai zenml secret create openai --api_key= ``` Then, you can use the hook in your pipeline: ```python from zenml.integration.openai.hooks import openai_chatgpt_alerter_failure_hook from zenml import step @step(on_failure=openai_chatgpt_alerter_failure_hook) def my_step(...): ... ``` If you had set up a Slack alerter as your alerter, for example, then you would see a message like this: ![OpenAI ChatGPT Failure Hook](../../../.gitbook/assets/failure\_alerter.png) You can use the suggestions as input that can help you fix whatever is going wrong in your code. If you have GPT-4 enabled for your account, you can use the `openai_gpt4_alerter_failure_hook` hook instead (imported from the same module).
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/use-pipeline-step-parameters.md ================ --- description: >- Steps and pipelines can be parameterized just like any other python function that you are familiar with. --- # Use pipeline/step parameters ## Parameters for your steps When calling a step in a pipeline, the inputs provided to the step function can either be an **artifact** or a **parameter**. An artifact represents the output of another step that was executed as part of the same pipeline and serves as a means to share data between steps. Parameters, on the other hand, are values provided explicitly when invoking a step. They are not dependent on the output of other steps and allow you to parameterize the behavior of your steps. {% hint style="warning" %} In order to allow the configuration of your steps using a configuration file, only values that can be serialized to JSON using Pydantic can be passed as parameters. If you want to pass other non-JSON-serializable objects such as NumPy arrays to your steps, use [External Artifacts](../../../user-guide/starter-guide/manage-artifacts.md#consuming-external-artifacts-within-a-pipeline) instead. {% endhint %} ```python from zenml import step, pipeline @step def my_step(input_1: int, input_2: int) -> None: pass @pipeline def my_pipeline(): int_artifact = some_other_step() # We supply the value of `input_1` as an artifact and # `input_2` as a parameter my_step(input_1=int_artifact, input_2=42) # We could also call the step with two artifacts or two # parameters instead: # my_step(input_1=int_artifact, input_2=int_artifact) # my_step(input_1=1, input_2=2) ``` Parameters of steps and pipelines can also be passed in using YAML configuration files. The following configuration file and Python code can work together and give you the flexibility to update configuration only in YAML file, once needed: ```yaml # config.yaml # these are parameters of the pipeline parameters: environment: production steps: my_step: # these are parameters of the step `my_step` parameters: input_2: 42 ``` ```python from zenml import step, pipeline @step def my_step(input_1: int, input_2: int) -> None: ... # input `environment` will come from the configuration file, # and it is evaluated to `production` @pipeline def my_pipeline(environment: str): ... if __name__=="__main__": my_pipeline.with_options(config_paths="config.yaml")() ``` {% hint style="warning" %} There might be conflicting settings for step or pipeline inputs, while working with YAML configuration files. Such situations happen when you define a step or a pipeline parameter in the configuration file and override it from the code later on. Don't worry - once it happens you will be informed with details and instructions how to fix. Example of such a conflict: ```yaml # config.yaml parameters: some_param: 24 steps: my_step: parameters: input_2: 42 ``` ```python # run.py from zenml import step, pipeline @step def my_step(input_1: int, input_2: int) -> None: pass @pipeline def my_pipeline(some_param: int): # here an error will be raised since `input_2` is # `42` in config, but `43` was provided in the code my_step(input_1=42, input_2=43) if __name__=="__main__": # here an error will be raised since `some_param` is # `24` in config, but `23` was provided in the code my_pipeline(23) ``` {% endhint %} **Parameters and caching** When an input is passed as a parameter, the step will only be cached if all parameter values are exactly the same as for previous executions of the step. **Artifacts and caching** When an artifact is used as a step function input, the step will only be cached if all the artifacts are exactly the same as for previous executions of the step. This means that if any of the upstream steps that produce the input artifacts for a step were not cached, the step itself will always be executed. *** ### See Also:
Use configuration files to set parametersuse-pipeline-step-parameters.md
How caching works and how to control itcontrol-caching-behavior.md
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/build-pipelines/using-a-custom-step-invocation-id.md ================ # Using a custom step invocation ID When calling a ZenML step as part of your pipeline, it gets assigned a unique **invocation ID** that you can use to reference this step invocation when [defining the execution order](control-execution-order-of-steps.md) of your pipeline steps or use it to [fetch information](fetching-pipelines.md) about the invocation after the pipeline has finished running. ```python from zenml import pipeline, step @step def my_step() -> None: ... @pipeline def example_pipeline(): # When calling a step for the first time inside a pipeline, # the invocation ID will be equal to the step name -> `my_step`. my_step() # When calling the same step again, the suffix `_2`, `_3`, ... will # be appended to the step name to generate a unique invocation ID. # For this call, the invocation ID would be `my_step_2`. my_step() # If you want to use a custom invocation ID when calling a step, you can # do so by passing it like this. If you pass a custom ID, it needs to be # unique for all the step invocations that happen as part of this pipeline. my_step(id="my_custom_invocation_id") ```
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/configure-python-environments/configure-the-server-environment.md ================ --- description: How to configure the server environment --- # Configure the server environment The ZenML server environment is configured using environment variables. You will need to set these before deploying your server instance. Please refer to [the full list of environment variables](../../../reference/environment-variables.md) available to you [here](../../../reference/environment-variables.md).
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/configure-python-environments/handling-dependencies.md ================ --- description: How to handle issues with conflicting dependencies --- # Handling dependencies This page documents a some of the common issues that arise when using ZenML with other libraries. When using ZenML with other libraries, you may encounter issues with conflicting dependencies. ZenML aims to be stack- and integration-agnostic, allowing you to run your pipelines using the tools that make sense for your problems. With this flexibility comes the possibility of dependency conflicts. ZenML allows you to install dependencies required by integrations through the `zenml integration install ...` command. This is a convenient way to install dependencies for a specific integration, but it can also lead to dependency conflicts if you are using other libraries in your environment. An easy way to see if the ZenML requirements are still met (after installing any extra dependencies required by your work) by running `zenml integration list` and checking that your desired integrations still bear the green tick symbol denoting that all requirements are met. ## Suggestions for Resolving Dependency Conflicts ### Use a tool like `pip-compile` for reproducibility Consider using a tool like `pip-compile` (available through [the `pip-tools` package](https://pip-tools.readthedocs.io/)) to compile your dependencies into a static `requirements.txt` file that can be used across environments. (If you are using [`uv`](https://github.com/astral-sh/uv), you might want to use `uv pip compile` as an alternative.) For a practical example and explanation of using `pip-compile` to address exactly this need, see [our 'gitflow' repository and workflow](https://github.com/zenml-io/zenml-gitflow#-software-requirements-management) to learn more. ### Use `pip check` to discover dependency conflicts Running [`pip check`](https://pip.pypa.io/en/stable/cli/pip\_check/) will verify that your environment's dependencies are compatible with one another. If not, you will see a list of the conflicts. This may or may not be a problem or something that will prevent you from moving forward with your specific use case, but it is certainly worth being aware of whether this is the case. ### Well-known dependency resolution issues Some of ZenML's integrations come with strict dependency and package version requirements. We try to keep these dependency requirements ranges as wide as possible for the integrations developed by ZenML, but it is not always possible to make this work completely smoothly. Here is one of the known issues: * `click`: ZenML currently requires `click~=8.0.3` for its CLI. This is on account of another dependency of ZenML. Using versions of `click` in your own project that are greater than 8.0.3 may cause unanticipated behaviors. ### Manually bypassing ZenML's integration installation It is possible to skip ZenML's integration installation process and install dependencies manually. This is not recommended, but it is possible and can be run at your own risk. {% hint style="info" %} Note that the `zenml integration install ...` command runs a `pip install ...` under the hood as part of its implementation, taking the dependencies listed in the integration object and installing them. For example, `zenml integration install gcp` will run `pip install "kfp==1.8.16" "gcsfs" "google-cloud-secret-manager" ...` and so on, since they are [specified in the integration definition](https://github.com/zenml-io/zenml/blob/ec2283473e5e0c5a2f1b7868875539a83e617f8c/src/zenml/integrations/gcp/\_\_init\_\_.py#L45). {% endhint %} To do this, you will need to install the dependencies for the integration you want to use manually. You can find the dependencies for the integrations by running the following: ```bash # to have the requirements exported to a file zenml integration export-requirements --output-file integration-requirements.txt INTEGRATION_NAME # to have the requirements printed to the console zenml integration export-requirements INTEGRATION_NAME ``` You can then amend and tweak those requirements as you see fit. Note that if you are using a remote orchestrator, you would then have to place the updated versions for the dependencies in a `DockerSettings` object (described in detail [here](../../../how-to/customize-docker-builds/docker-settings-on-a-pipeline.md)) which will then make sure everything is working as you need.
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/configure-python-environments/README.md ================ --- icon: python description: Navigating multiple development environments. --- # Configure python environments ZenML deployments often involve multiple environments. This guide helps you manage dependencies and configurations across these environments. Here is a visual overview of the different environments:

Left box is the client environment, middle is the zenml server environment, and the right most contains the build environments

## Client Environment (or the Runner environment) The client environment (sometimes known as the runner environment) is where the ZenML pipelines are _compiled_, i.e., where you call the pipeline function (typically in a `run.py` script). There are different types of client environments: * A local development environment * A CI runner in production. * A [ZenML Pro](https://zenml.io/pro) runner. * A `runner` image orchestrated by the ZenML server to start pipelines. In all the environments, you should use your preferred package manager (e.g., `pip` or `poetry`) to manage dependencies. Ensure you install the ZenML package and any required [integrations](../../../component-guide/README.md). The client environment typically follows these key steps when starting a pipeline: 1. Compiling an intermediate pipeline representation via the `@pipeline` function. 2. Creating or triggering [pipeline and step build environments](../../../component-guide/image-builders/image-builders.md) if running remotely. 3. Triggering a run in the [orchestrator](../../../component-guide/orchestrators/orchestrators.md). Please note that the `@pipeline` function in your code is **only ever called** in this environment. Therefore, any computational logic that is executed in the pipeline function needs to be relevant to this so-called _compile time_, rather than at _execution_ time, which happens later. ## ZenML Server Environment The ZenML server environment is a FastAPI application managing pipelines and metadata. It includes the ZenML Dashboard and is accessed when you [deploy ZenML](../../../getting-started/deploying-zenml/README.md). To manage dependencies, install them during [ZenML deployment](../../../getting-started/deploying-zenml/README.md), but only if you have custom integrations, as most are built-in. See also [here](./configure-the-server-environment.md) for more on [configuring the server environment](./configure-the-server-environment.md). ## Execution Environments When running locally, there is no real concept of an `execution` environment as the client, server, and execution environment are all the same. However, when running a pipeline remotely, ZenML needs to transfer your code and environment over to the remote [orchestrator](../../../component-guide/orchestrators/orchestrators.md). In order to achieve this, ZenML builds Docker images known as `execution environments`. ZenML handles the Docker image configuration, creation, and pushing, starting with a [base image](https://hub.docker.com/r/zenmldocker/zenml) containing ZenML and Python, then adding pipeline dependencies. To manage the Docker image configuration, follow the steps in the [containerize your pipeline](../../../how-to/customize-docker-builds/README.md) guide, including specifying additional pip dependencies, using a custom parent image, and customizing the build process. ## Image Builder Environment By default, execution environments are created locally in the [client environment](#client-environment-or-the-runner-environment) using the local Docker client. However, this requires Docker installation and permissions. ZenML offers [image builders](../../../component-guide/image-builders/image-builders.md), a special [stack component](../../../component-guide/README.md), allowing users to build and push Docker images in a different specialized _image builder environment_. Note that even if you don't configure an image builder in your stack, ZenML still uses the [local image builder](../../../component-guide/image-builders/local.md) to retain consistency across all builds. In this case, the image builder environment is the same as the client environment.
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/develop-locally/keep-your-dashboard-server-clean.md ================ --- description: Learn how to keep your pipeline runs clean during development. --- # Keep your dashboard and server clean When developing pipelines, it's common to run and debug them multiple times. To avoid cluttering the server with these development runs, ZenML provides several options: ## Run locally One of the easiest ways to avoid cluttering a shared server / dashboard is to disconnect your client from the remote server and simply spin up a local server: ```bash zenml login --local ``` Note that there are some limitations to this approach, particularly if you want to use remote infrastructure, but if there are local runs that you can do without the need for remote infrastructure, this can be a quick and easy way to keep things clean. When you're ready to reconnect to the server to continue with your shared runs, you can simply run `zenml login ` again. ## Pipeline Runs ### Unlisted Runs Pipeline runs can be created without being explicitly associated with a pipeline by passing the `unlisted` parameter when running a pipeline: ```python pipeline_instance.run(unlisted=True) ``` Unlisted runs are not displayed on the pipeline's page in the dashboard (though they *are* displayed in the pipeline run section), keeping the pipeline's history clean and focused on the pipelines that matter most. ### Deleting Pipeline Runs If you want to delete a specific pipeline run, you can use a script like this: ```bash zenml pipeline runs delete ``` If you want to delete all pipeline runs in the last 24 hours, for example, you could run a script like this: ``` #!/usr/bin/env python3 import datetime from zenml.client import Client def delete_recent_pipeline_runs(): # Initialize ZenML client zc = Client() # Calculate the timestamp for 24 hours ago twenty_four_hours_ago = datetime.datetime.utcnow() - datetime.timedelta(hours=24) # Format the timestamp as required by ZenML time_filter = twenty_four_hours_ago.strftime("%Y-%m-%d %H:%M:%S") # Get the list of pipeline runs created in the last 24 hours recent_runs = zc.list_pipeline_runs(created=f"gt:{time_filter}") # Delete each run for run in recent_runs: print(f"Deleting run: {run.id} (Created: {run.body.created})") zc.delete_pipeline_run(run.id) print(f"Deleted {len(recent_runs)} pipeline runs.") if __name__ == "__main__": delete_recent_pipeline_runs() ``` For different time ranges you can update this as appropriate. ## Pipelines ### Deleting Pipelines Pipelines that are no longer needed can be deleted using the command: ```bash zenml pipeline delete ``` This allows you to start fresh with a new pipeline, removing all previous runs associated with the deleted pipeline. This is a slightly more drastic approach, but it can sometimes be useful to keep the development environment clean. ## Unique Pipeline Names Pipelines can be given unique names each time they are run to uniquely identify them. This helps differentiate between multiple iterations of the same pipeline during development. By default ZenML generates names automatically based on the current date and time, but you can pass in a `run_name` when defining the pipeline: ```python training_pipeline = training_pipeline.with_options( run_name="custom_pipeline_run_name" ) training_pipeline() ``` Note that pipeline names must be unique. For more information on this feature, see the [documentation on naming pipeline runs](../../../how-to/pipeline-development/build-pipelines/name-your-pipeline-runs.md). ## Models Models are something that you have to explicitly register or pass in as you define your pipeline, so to run a pipeline without it being attached to a model is fairly straightforward: simply don't do the things specified in our [documentation on registering models](../../model-management-metrics/model-control-plane/register-a-model.md). In order to delete a model or a specific model version, you can use the CLI or Python SDK to accomplish this. As an example, to delete all versions of a model, you can use: ```bash zenml model delete ``` See the full documentation on [how to delete models](../../model-management-metrics/model-control-plane/delete-a-model.md). ## Artifacts ### Pruning artifacts If you want to delete artifacts that are no longer referenced by any pipeline runs, you can use the following CLI command: ```bash zenml artifact prune ``` By default, this method deletes artifacts physically from the underlying artifact store AND also the entry in the database. You can control this behavior by using the `--only-artifact` and `--only-metadata` flags. For more information, see the [documentation for this artifact pruning feature](../../data-artifact-management/handle-data-artifacts/delete-an-artifact.md). ## Cleaning your environment As a more drastic measure, the `zenml clean` command can be used to start from scratch on your local machine. This will: - delete all pipelines, pipeline runs and associated metadata - delete all artifacts There is also a `--local` flag that you can set if you want to delete local files relating to the active stack. Note that `zenml clean` does not delete artifacts and pipelines on the server; it only deletes the local data and metadata. By utilizing these options, you can maintain a clean and organized pipeline dashboard, focusing on the runs that matter most for your project.
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/develop-locally/local-prod-pipeline-variants.md ================ --- description: Create different variants of your pipeline for local development and production. --- # Create pipeline variants for local development and production When developing ZenML pipelines, it's often beneficial to have different variants of your pipeline for local development and production environments. This approach allows you to iterate quickly during development while maintaining a full-scale setup for production. While configuration files are one way to achieve this, you can also implement this directly in your code. There are several ways to create different variants of your pipeline: 1. Using configuration files 2. Implementing variants in code 3. Using environment variables Let's explore each of these methods: ## Using configuration files ZenML allows you to specify pipeline and step configurations using YAML files. Here's an example: ```yaml enable_cache: False parameters: dataset_name: "small_dataset" steps: load_data: enable_cache: False ``` This config file sets up a development variant by using a smaller dataset and disabling caching. To apply this configuration to your pipeline, use the `with_options(config_path=)` pattern: ```python from zenml import step, pipeline @step def load_data(dataset_name: str) -> dict: ... @pipeline def ml_pipeline(dataset_name: str): load_data(dataset_name) if __name__ == "__main__": ml_pipeline.with_options(config_path="path/to/config.yaml")() ``` You can create separate configuration files for development and production: - `config_dev.yaml`: Configuration for local development - `config_prod.yaml`: Configuration for production ## Implementing variants in code You can also create pipeline variants directly in your code: ```python import os from zenml import step, pipeline @step def load_data(dataset_name: str) -> dict: # Load data based on the dataset name ... @pipeline def ml_pipeline(is_dev: bool = False): dataset = "small_dataset" if is_dev else "full_dataset" load_data(dataset) if __name__ == "__main__": is_dev = os.environ.get("ZENML_ENVIRONMENT") == "dev" ml_pipeline(is_dev=is_dev) ``` This approach allows you to switch between development and production variants using a simple boolean flag. ## Using environment variables You can use environment variables to determine which variant to run: ```python import os if os.environ.get("ZENML_ENVIRONMENT") == "dev": config_path = "config_dev.yaml" else: config_path = "config_prod.yaml" ml_pipeline.with_options(config_path=config_path)() ``` Run your pipeline with: `ZENML_ENVIRONMENT=dev python run.py` or `ZENML_ENVIRONMENT=prod python run.py`. ## Development variant considerations When creating a development variant of your pipeline, consider optimizing these aspects for faster iteration and debugging: - Use smaller datasets for quicker runs - Specify a local stack for execution - Reduce number of training epochs - Decrease batch size - Use a smaller base model For example, in a configuration file: ```yaml parameters: dataset_path: "data/small_dataset.csv" epochs: 1 batch_size: 16 stack: local_stack ``` Or in code: ```python @pipeline def ml_pipeline(is_dev: bool = False): dataset = "data/small_dataset.csv" if is_dev else "data/full_dataset.csv" epochs = 1 if is_dev else 100 batch_size = 16 if is_dev else 64 load_data(dataset) train_model(epochs=epochs, batch_size=batch_size) ``` By creating different variants of your pipeline, you can quickly test and debug your code locally with a lightweight setup, while maintaining a full-scale configuration for production execution. This approach streamlines your development workflow and allows for efficient iteration without compromising your production pipeline.
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/develop-locally/README.md ================ --- icon: house description: Learn how to develop your pipelines locally. --- # Develop locally This section contains information around best practices for developing your pipelines locally. It's common to do at least some work locally where you can iterate faster, and where it doesn't take much time or money to run your pipeline. People often do this with a smaller subset of their data, or with synthetic data. ZenML supports this pattern and the sections that follow guide you through this pattern of working locally and then (at certain moments) pushing and running your pipelines on more powerful remote hardware.
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/run-remote-notebooks/limitations-of-defining-steps-in-notebook-cells.md ================ # Limitations of defining steps in notebook cells If you want to run ZenML steps defined in notebook cells remotely (either with a remote [orchestrator](../../../component-guide/orchestrators/orchestrators.md) or [step operator](../../../component-guide/step-operators/step-operators.md)), the cells defining your steps must meet the following conditions: - The cell can only contain python code, no Jupyter magic commands or shell commands starting with a `%` or `!`. - The cell **must not** call code from other notebook cells. Functions or classes imported from python files are allowed. - The cell **must not** rely on imports of previous cells. This means your cell must perform all the imports it needs itself, including ZenML imports like `from zenml import step`.
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/run-remote-notebooks/README.md ================ --- icon: notebook description: Use Jupyter Notebooks to run remote steps or pipelines --- # Run remote pipelines from notebooks ZenML steps and pipelines can be defined in a Jupyter notebook and executed remotely. To do so, ZenML will extract the code from your notebook cells and run them as Python modules inside the Docker containers that execute your pipeline steps remotely. For this to work, the notebook cells in which you define your steps need to meet certain conditions. Learn more about it in the following sections:
Limitations of defining steps in notebook cellslimitations-of-defining-steps-in-notebook-cells.md
Run a single step from a notebookrun-a-single-step-from-a-notebook.md
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/run-remote-notebooks/run-a-single-step-from-a-notebook.md ================ # Run a single step from a notebook If you want to run just a single step remotely from a notebook, you can simply call the step as you would with a normal Python function. ZenML will internally create a pipeline with just your step and run it on the active stack. {% hint style="warning" %} When defining a step that should be run remotely in a notebook, make sure you're aware of all the [limitations](limitations-of-defining-steps-in-notebook-cells.md) that apply. {% endhint %} ```python from zenml import step import pandas as pd from sklearn.base import ClassifierMixin from sklearn.svm import SVC # Configure the step to use a step operator. If you're not using # a step operator, you can remove this and the step will run on # your orchestrator instead. @step(step_operator="") def svc_trainer( X_train: pd.DataFrame, y_train: pd.Series, gamma: float = 0.001, ) -> Tuple[ Annotated[ClassifierMixin, "trained_model"], Annotated[float, "training_acc"], ]: """Train a sklearn SVC classifier.""" model = SVC(gamma=gamma) model.fit(X_train.to_numpy(), y_train.to_numpy()) train_acc = model.score(X_train.to_numpy(), y_train.to_numpy()) print(f"Train accuracy: {train_acc}") return model, train_acc X_train = pd.DataFrame(...) y_train = pd.Series(...) # Call the step directly. This will internally create a # pipeline with just this step, which will be executed on # the active stack. model, train_acc = svc_trainer(X_train=X_train, y_train=y_train) ```
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/training-with-gpus/accelerate-distributed-training.md ================ --- description: Run distributed training with Hugging Face's Accelerate library in ZenML pipelines. --- # Distributed training with 🤗 Accelerate There are several reasons why you might want to scale your machine learning pipelines to utilize distributed training, such as leveraging multiple GPUs or training across multiple nodes. ZenML now integrates with [Hugging Face's Accelerate library](https://github.com/huggingface/accelerate) to make this process seamless and efficient. ## Use 🤗 Accelerate in your steps Some steps in your machine learning pipeline, particularly training steps, can benefit from distributed execution. You can now use the `run_with_accelerate` decorator to enable this: ```python from zenml import step, pipeline from zenml.integrations.huggingface.steps import run_with_accelerate @run_with_accelerate(num_processes=4, multi_gpu=True) @step def training_step(some_param: int, ...): # your training code is below ... @pipeline def training_pipeline(some_param: int, ...): training_step(some_param, ...) ``` The `run_with_accelerate` decorator wraps your step, enabling it to run with Accelerate's distributed training capabilities. It accepts arguments available to `accelerate launch` CLI command. {% hint style="info" %} For a complete list of available arguments and more details, refer to the [Accelerate CLI documentation](https://huggingface.co/docs/accelerate/en/package_reference/cli#accelerate-launch). {% endhint %} ### Configuration The `run_with_accelerate` decorator accepts various arguments to configure your distributed training environment. Some common arguments include: - `num_processes`: The number of processes to use for distributed training. - `cpu`: Whether to force training on CPU. - `multi_gpu`: Whether to launch distributed GPU training. - `mixed_precision`: Mixed precision training mode ('no', 'fp16', or 'bf16'). ### Important Usage Notes 1. The `run_with_accelerate` decorator can only be used directly on steps using the '@' syntax. Using it as a function inside the pipeline definition is not allowed. 2. Accelerated steps do not support positional arguments. Use keyword arguments when calling your steps. 3. If `run_with_accelerate` is misused, it will raise a `RuntimeError` with a helpful message explaining the correct usage. {% hint style="info" %} To see a full example where Accelerate is used within a ZenML pipeline, check out our [llm-lora-finetuning](https://github.com/zenml-io/zenml-projects/blob/main/llm-lora-finetuning/README.md) project which leverages the distributed training functionalities while finetuning an LLM. {% endhint %} ## Ensure your container is Accelerate-ready To run steps with Accelerate, it's crucial to have the necessary dependencies installed in the environment. This section will guide you on how to configure your environment to utilize Accelerate effectively. {% hint style="warning" %} Note that these configuration changes are **required** for Accelerate to function properly. If you don't update the settings, your steps might run, but they will not leverage distributed training capabilities. {% endhint %} All steps using Accelerate will be executed within a containerized environment. Therefore, you need to make two amendments to your Docker settings for the relevant steps: ### 1. Specify a CUDA-enabled parent image in your `DockerSettings` For complete details, refer to the [containerization page](../../customize-docker-builds/README.md). Here's an example using a CUDA-enabled PyTorch image: ```python from zenml import pipeline from zenml.config import DockerSettings docker_settings = DockerSettings(parent_image="pytorch/pytorch:1.12.1-cuda11.3-cudnn8-runtime") @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` ### 2. Add Accelerate as explicit pip requirements Ensure that Accelerate is installed in your container: ```python from zenml.config import DockerSettings from zenml import pipeline docker_settings = DockerSettings( parent_image="pytorch/pytorch:1.12.1-cuda11.3-cudnn8-runtime", requirements=["accelerate", "torchvision"] ) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` ## Train across multiple GPUs ZenML's Accelerate integration supports training your models with multiple GPUs on a single node or across multiple nodes. This is particularly useful for large datasets or complex models that benefit from parallelization. In practice, using Accelerate with multiple GPUs involves: - Wrapping your training step with the `run_with_accelerate` function in your pipeline definition - Configuring the appropriate Accelerate arguments (e.g., `num_processes`, `multi_gpu`) - Ensuring your training code is compatible with distributed training (Accelerate handles most of this automatically) {% hint style="info" %} If you're new to distributed training or encountering issues, please [connect with us on Slack](https://zenml.io/slack) and we'll be happy to assist you. {% endhint %} By leveraging the Accelerate integration in ZenML, you can easily scale your training processes and make the most of your available hardware resources, all while maintaining the structure and benefits of your ZenML pipelines.
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/training-with-gpus/README.md ================ --- icon: microchip-ai description: Ensuring your pipelines or steps run on GPU-backed hardware. --- # Specify cloud resources There are several reasons why you may want to scale your machine learning pipelines to the cloud, such as utilizing more powerful hardware or distributing tasks across multiple nodes. In order to achieve this with ZenML you'll need to run your steps on GPU-backed hardware using `ResourceSettings` to allocate greater resources on an orchestrator node and/or make some adjustments to the container environment. ## Specify resource requirements for steps Some steps of your machine learning pipeline might be more resource-intensive and require special hardware to execute. In such cases, you can specify the required resources for steps as follows: ```python from zenml.config import ResourceSettings from zenml import step @step(settings={"resources": ResourceSettings(cpu_count=8, gpu_count=2, memory="8GB")}) def training_step(...) -> ...: # train a model ``` If the underlying [orchestrator](../../../component-guide/orchestrators/orchestrators.md) in your stack then supports specifying resources, this setting will attempt to secure these resources. Some orchestrators (like the [Skypilot orchestrator](../../../component-guide/orchestrators/skypilot-vm.md)) do not support `ResourceSettings` directly, but rather use their `Orchestrator` specific settings to achieve the same effect: ```python from zenml import step from zenml.integrations.skypilot.flavors.skypilot_orchestrator_aws_vm_flavor import SkypilotAWSOrchestratorSettings skypilot_settings = SkypilotAWSOrchestratorSettings( cpus="2", memory="16", accelerators="V100:2", ) @step(settings={"orchestrator": skypilot_settings) def training_step(...) -> ...: # train a model ``` Please refer to the source code and documentation of each orchestrator to find out which orchestrator supports specifying resources in what way. {% hint style="info" %} If you're using an orchestrator which does not support this feature or its underlying infrastructure does not cover your requirements, you can also take a look at [step operators](../../../component-guide/step-operators/step-operators.md) which allow you to execute individual steps of your pipeline in environments independent of your orchestrator. {% endhint %} ### Ensure your container is CUDA-enabled To run steps or pipelines on GPUs, it's crucial to have the necessary CUDA tools installed in the environment. This section will guide you on how to configure your environment to utilize GPU capabilities effectively. {% hint style="warning" %} Note that these configuration changes are **required** for the GPU hardware to be properly utilized. If you don't update the settings, your steps might run, but they will not see any boost in performance from the custom hardware. {% endhint %} All steps running on GPU-backed hardware will be executed within a containerized environment, whether you're using the local Docker orchestrator or a cloud instance of Kubeflow. Therefore, you need to make two amendments to your Docker settings for the relevant steps: #### 1. **Specify a CUDA-enabled parent image in your `DockerSettings`** For complete details, refer to the [containerization page](../../../how-to/customize-docker-builds/README.md) that explains how to do this. As an example, if you want to use the latest CUDA-enabled official PyTorch image for your entire pipeline run, you can include the following code: ```python from zenml import pipeline from zenml.config import DockerSettings docker_settings = DockerSettings(parent_image="pytorch/pytorch:1.12.1-cuda11.3-cudnn8-runtime") @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` For TensorFlow, you might use the `tensorflow/tensorflow:latest-gpu` image, as detailed in the [official TensorFlow documentation](https://www.tensorflow.org/install/docker#gpu\_support) or their [DockerHub overview](https://hub.docker.com/r/tensorflow/tensorflow). #### 2. **Add ZenML as an explicit pip requirement** ZenML requires that ZenML itself be installed for the containers running your pipelines and steps. Therefore, you need to explicitly state that ZenML should be installed. There are several ways to specify this, but as an example, you can update the code from above as follows: ```python from zenml.config import DockerSettings from zenml import pipeline docker_settings = DockerSettings( parent_image="pytorch/pytorch:1.12.1-cuda11.3-cudnn8-runtime", requirements=["zenml==0.39.1", "torchvision"] ) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` Adding these two extra settings options will ensure that CUDA is enabled for the specific steps that require GPU acceleration. Be cautious when choosing the image to avoid confusion when switching between local and remote environments. For example, you might have one version of PyTorch installed locally with a particular CUDA version, but when you switch to your remote stack or environment, you might be forced to use a different CUDA version. The core cloud operators offer prebuilt Docker images that fit with their hardware. You can find more information on them here: * [AWS](https://github.com/aws/deep-learning-containers/blob/master/available\_images.md) * [GCP](https://cloud.google.com/deep-learning-vm/docs/images) * [Azure](https://learn.microsoft.com/en-us/azure/machine-learning/concept-prebuilt-docker-images-inference) Not all of these images are available on DockerHub, so ensure that the orchestrator environment your pipeline runs in has sufficient permissions to pull images from registries if you are using one of those. ### Reset the CUDA cache in between steps Your use case will determine whether this is necessary or makes sense to do, but we have seen that resetting the CUDA cache in between steps can help avoid issues with the GPU cache. This is particularly necessary if your training jobs are pushing the boundaries of the GPU cache. Doing so is simple; just use a helper function to reset the cache at the beginning of any GPU-enabled steps. For example, something as simple as this might suffice: ```python import gc import torch def cleanup_memory() -> None: while gc.collect(): torch.cuda.empty_cache() ``` You can then call this function at the beginning of your GPU-enabled steps: ```python from zenml import step @step def training_step(...): cleanup_memory() # train a model ``` Note that resetting the memory cache will potentially affect others using the same GPU, so use this judiciously. ## Train across multiple GPUs ZenML supports training your models with multiple GPUs on a single node. This is useful if you have a large dataset and want to train your model in parallel. The most important thing that you'll have to handle is preventing multiple ZenML instances from being spawned as you split the work among multiple GPUs. In practice this will probably involve: - creating a script / Python function that contains the logic of training your model (with the specification that this should run in parallel across multiple GPUs) - calling that script / external function from within the step, possibly with some wrapper or helper code to dynamically configure or update the external script function We're aware that this is not the most elegant solution and we're at work to implement a better option with some inbuilt support for this task. If this is something you're struggling with and need support getting the step code working, please do [connect with us on Slack](https://zenml.io/slack) and we'll do our best to help you out.
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/use-configuration-files/autogenerate-a-template-yaml-file.md ================ --- description: >- To help you figure out what you can put in your configuration file, simply autogenerate a template. --- # Autogenerate a template yaml file If you want to generate a template yaml file of your specific pipeline, you can do so by using the `.write_run_configuration_template()` method. This will generate a yaml file with all options commented out. This way you can pick and choose the settings that are relevant to you. ```python from zenml import pipeline ... @pipeline(enable_cache=True) # set cache behavior at step level def simple_ml_pipeline(parameter: int): dataset = load_data(parameter=parameter) train_model(dataset) simple_ml_pipeline.write_run_configuration_template(path="") ```
An example of a generated YAML configuration template ```yaml build: Union[PipelineBuildBase, UUID, NoneType] enable_artifact_metadata: Optional[bool] enable_artifact_visualization: Optional[bool] enable_cache: Optional[bool] enable_step_logs: Optional[bool] extra: Mapping[str, Any] model: audience: Optional[str] description: Optional[str] ethics: Optional[str] license: Optional[str] limitations: Optional[str] name: str save_models_to_registry: bool suppress_class_validation_warnings: bool tags: Optional[List[str]] trade_offs: Optional[str] use_cases: Optional[str] version: Union[ModelStages, int, str, NoneType] parameters: Optional[Mapping[str, Any]] run_name: Optional[str] schedule: catchup: bool cron_expression: Optional[str] end_time: Optional[datetime] interval_second: Optional[timedelta] name: Optional[str] run_once_start_time: Optional[datetime] start_time: Optional[datetime] settings: docker: apt_packages: List[str] build_context_root: Optional[str] build_options: Mapping[str, Any] copy_files: bool copy_global_config: bool dockerfile: Optional[str] dockerignore: Optional[str] environment: Mapping[str, Any] install_stack_requirements: bool parent_image: Optional[str] python_package_installer: PythonPackageInstaller replicate_local_python_environment: Union[List[str], PythonEnvironmentExportMethod, NoneType] required_integrations: List[str] requirements: Union[NoneType, str, List[str]] skip_build: bool prevent_build_reuse: bool allow_including_files_in_images: bool allow_download_from_code_repository: bool allow_download_from_artifact_store: bool target_repository: str user: Optional[str] resources: cpu_count: Optional[PositiveFloat] gpu_count: Optional[NonNegativeInt] memory: Optional[ConstrainedStrValue] steps: load_data: enable_artifact_metadata: Optional[bool] enable_artifact_visualization: Optional[bool] enable_cache: Optional[bool] enable_step_logs: Optional[bool] experiment_tracker: Optional[str] extra: Mapping[str, Any] failure_hook_source: attribute: Optional[str] module: str type: SourceType model: audience: Optional[str] description: Optional[str] ethics: Optional[str] license: Optional[str] limitations: Optional[str] name: str save_models_to_registry: bool suppress_class_validation_warnings: bool tags: Optional[List[str]] trade_offs: Optional[str] use_cases: Optional[str] version: Union[ModelStages, int, str, NoneType] name: Optional[str] outputs: output: default_materializer_source: attribute: Optional[str] module: str type: SourceType materializer_source: Optional[Tuple[Source, ...]] parameters: {} settings: docker: apt_packages: List[str] build_context_root: Optional[str] build_options: Mapping[str, Any] copy_files: bool copy_global_config: bool dockerfile: Optional[str] dockerignore: Optional[str] environment: Mapping[str, Any] install_stack_requirements: bool parent_image: Optional[str] python_package_installer: PythonPackageInstaller replicate_local_python_environment: Union[List[str], PythonEnvironmentExportMethod, NoneType] required_integrations: List[str] requirements: Union[NoneType, str, List[str]] skip_build: bool prevent_build_reuse: bool allow_including_files_in_images: bool allow_download_from_code_repository: bool allow_download_from_artifact_store: bool target_repository: str user: Optional[str] resources: cpu_count: Optional[PositiveFloat] gpu_count: Optional[NonNegativeInt] memory: Optional[ConstrainedStrValue] step_operator: Optional[str] success_hook_source: attribute: Optional[str] module: str type: SourceType train_model: enable_artifact_metadata: Optional[bool] enable_artifact_visualization: Optional[bool] enable_cache: Optional[bool] enable_step_logs: Optional[bool] experiment_tracker: Optional[str] extra: Mapping[str, Any] failure_hook_source: attribute: Optional[str] module: str type: SourceType model: audience: Optional[str] description: Optional[str] ethics: Optional[str] license: Optional[str] limitations: Optional[str] name: str save_models_to_registry: bool suppress_class_validation_warnings: bool tags: Optional[List[str]] trade_offs: Optional[str] use_cases: Optional[str] version: Union[ModelStages, int, str, NoneType] name: Optional[str] outputs: {} parameters: {} settings: docker: apt_packages: List[str] build_context_root: Optional[str] build_options: Mapping[str, Any] copy_files: bool copy_global_config: bool dockerfile: Optional[str] dockerignore: Optional[str] environment: Mapping[str, Any] install_stack_requirements: bool parent_image: Optional[str] python_package_installer: PythonPackageInstaller replicate_local_python_environment: Union[List[str], PythonEnvironmentExportMethod, NoneType] required_integrations: List[str] requirements: Union[NoneType, str, List[str]] skip_build: bool prevent_build_reuse: bool allow_including_files_in_images: bool allow_download_from_code_repository: bool allow_download_from_artifact_store: bool target_repository: str user: Optional[str] resources: cpu_count: Optional[PositiveFloat] gpu_count: Optional[NonNegativeInt] memory: Optional[ConstrainedStrValue] step_operator: Optional[str] success_hook_source: attribute: Optional[str] module: str type: SourceType ```
{% hint style="info" %} When you want to configure your pipeline with a certain stack in mind, you can do so as well:\ \`...write\_run\_configuration\_template(stack=\) {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/use-configuration-files/configuration-hierarchy.md ================ --- description: >- When things can be configured on the pipeline and step level, the step configuration overrides the pipeline. --- # Configuration hierarchy There are a few general rules when it comes to settings and configurations that are applied in multiple places. Generally the following is true: * Configurations in code override configurations made inside of the yaml file * Configurations at the step level override those made at the pipeline level * In case of attributes the dictionaries are merged ```python from zenml import pipeline, step from zenml.config import ResourceSettings @step def load_data(parameter: int) -> dict: ... @step(settings={"resources": ResourceSettings(gpu_count=1, memory="2GB")}) def train_model(data: dict) -> None: ... @pipeline(settings={"resources": ResourceSettings(cpu_count=2, memory="1GB")}) def simple_ml_pipeline(parameter: int): ... # ZenMl merges the two configurations and uses the step configuration to override # values defined on the pipeline level train_model.configuration.settings["resources"] # -> cpu_count: 2, gpu_count=1, memory="2GB" simple_ml_pipeline.configuration.settings["resources"] # -> cpu_count: 2, memory="1GB" ```
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/use-configuration-files/how-to-use-config.md ================ --- description: Specify a configuration file --- # 📃 Use configuration files {% hint style="info" %} All configuration that can be specified in a YAML file can also be specified in code itself. However, it is best practice to use a YAML file to separate config from code. {% endhint %} You can use the `with_options(config_path=)` pattern to apply your configuration to a pipeline. Here is a minimal example of using a file based configuration yaml. ```yaml enable_cache: False # Configure the pipeline parameters parameters: dataset_name: "best_dataset" steps: load_data: # Use the step name here enable_cache: False # same as @step(enable_cache=False) ``` ```python from zenml import step, pipeline @step def load_data(dataset_name: str) -> dict: ... @pipeline # This function combines steps together def simple_ml_pipeline(dataset_name: str): load_data(dataset_name) if __name__=="__main__": simple_ml_pipeline.with_options(config_path=)() ``` The above would run the `simple_ml_pipeline` with cache disabled for `load_data` and the parameter `dataset_name` set to `best_dataset`.
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/use-configuration-files/README.md ================ --- icon: file-lines description: ZenML makes it easy to configure and run a pipeline with configuration files. --- # Use configuration files ZenML pipelines can be configured at runtime with a simple YAML file that can help you set [parameters](../../pipeline-development/build-pipelines/use-pipeline-step-parameters.md), control [caching behavior](../../pipeline-development/build-pipelines/control-caching-behavior.md) or even configure different stack components. Learn more about the different options in the following sections:
What can be configuredwhat-can-be-configured.md
Configuration hierarchyconfiguration-hierarchy.md
Autogenerate a template yaml fileautogenerate-a-template-yaml-file.md
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/use-configuration-files/retrieve-used-configuration-of-a-run.md ================ # Find out which configuration was used for a run Sometimes you might want to extract the used configuration from a pipeline that has already run. You can do this simply by loading the pipeline run and accessing its `config` attribute or the `config` attribute of one of its steps. ```python from zenml.client import Client pipeline_run = Client().get_pipeline_run() # General configuration for the pipeline pipeline_run.config # Configuration for a specific step pipeline_run.steps[].config ```
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/use-configuration-files/runtime-configuration.md ================ --- description: Using settings to configure runtime configuration. --- # Stack component specific configuration {% embed url="https://www.youtube.com/embed/AdwW6DlCWFE" %} Stack Component Config vs Settings in ZenML {% endembed %} Part of the configuration of a pipeline are its `Settings`. These allow you to configure runtime configurations for stack components and pipelines. Concretely, they allow you to configure: * The [resources](../../advanced-topics/training-with-gpus/training-with-gpus.md#specify-resource-requirements-for-steps) required for a step * Configuring the [containerization](../../../how-to/customize-docker-builds/README.md) process of a pipeline (e.g. What requirements get installed in the Docker image) * Stack component-specific configuration, e.g., if you have an experiment tracker passing in the name of the experiment at runtime You will learn about all of the above in more detail later, but for now, let's try to understand that all of this configuration flows through one central concept called `BaseSettings`. (From here on, we use `settings` and `BaseSettings` as analogous in this guide). ## Types of settings Settings are categorized into two types: * **General settings** that can be used on all ZenML pipelines. Examples of these are: * [`DockerSettings`](../../../how-to/customize-docker-builds/README.md) to specify Docker settings. * [`ResourceSettings`](../../../how-to/pipeline-development/training-with-gpus/README.md) to specify resource settings. * **Stack-component-specific settings**: These can be used to supply runtime configurations to certain stack components (the key should be `` or `.`). Settings for components not in the active stack will be ignored. Examples of these are: * [`SkypilotAWSOrchestratorSettings`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-skypilot_aws/#zenml.integrations.skypilot_aws.flavors.skypilot_orchestrator_aws_vm_flavor.SkypilotAWSOrchestratorSettings) to specify Skypilot settings (works for `SkypilotGCPOrchestratorSettings` and `SkypilotAzureOrchestratorSettings` as well). * [`KubeflowOrchestratorSettings`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-kubeflow/#zenml.integrations.kubeflow.flavors.kubeflow_orchestrator_flavor.KubeflowOrchestratorSettings) to specify Kubeflow settings. * [`MLflowExperimentTrackerSettings`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-mlflow/#zenml.integrations.mlflow.flavors.mlflow_experiment_tracker_flavor.MLFlowExperimentTrackerSettings) to specify MLflow settings. * [`WandbExperimentTrackerSettings`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-wandb/#zenml.integrations.wandb.flavors.wandb_experiment_tracker_flavor.WandbExperimentTrackerSettings) to specify W\&B settings. * [`WhylogsDataValidatorSettings`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-whylogs/#zenml.integrations.whylogs.flavors.whylogs_data_validator_flavor.WhylogsDataValidatorSettings) to specify Whylogs settings. * [`SagemakerStepOperatorSettings`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-aws/#zenml.integrations.aws.flavors.sagemaker_step_operator_flavor.SagemakerStepOperatorSettings) to specify AWS Sagemaker step operator settings. * [`VertexStepOperatorSettings`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-gcp/#zenml.integrations.gcp.flavors.vertex_step_operator_flavor.VertexStepOperatorSettings) to specify GCP Vertex step operator settings. * [`AzureMLStepOperatorSettings`](https://sdkdocs.zenml.io/latest/integration_code_docs/integrations-azure/#zenml.integrations.azure.flavors.azureml_step_operator_flavor.AzureMLStepOperatorSettings) to specify AzureML step operator settings. ### Difference between stack component settings at registration-time vs real-time For stack-component-specific settings, you might be wondering what the difference is between these and the configuration passed in while doing `zenml stack-component register --config1=configvalue --config2=configvalue`, etc. The answer is that the configuration passed in at registration time is static and fixed throughout all pipeline runs, while the settings can change. A good example of this is the [`MLflow Experiment Tracker`](../../../component-guide/experiment-trackers/mlflow.md), where configuration which remains static such as the `tracking_url` is sent through at registration time, while runtime configuration such as the `experiment_name` (which might change every pipeline run) is sent through as runtime settings. Even though settings can be overridden at runtime, you can also specify _default_ values for settings while configuring a stack component. For example, you could set a default value for the `nested` setting of your MLflow experiment tracker: `zenml experiment-tracker register --flavor=mlflow --nested=True` This means that all pipelines that run using this experiment tracker use nested MLflow runs unless overridden by specifying settings for the pipeline at runtime. ### Using the right key for Stack-component-specific settings When specifying stack-component-specific settings, a key needs to be passed. This key should always correspond to the pattern: `` or `.`. If you specify just the category (e.g. `step_operator` or `orchestrator`), ZenML will try to apply those settings to whatever flavor of component is in your stack when running a pipeline. If your settings don't apply to this flavor, they will be ignored. For example, the [SagemakerStepOperator](../../../component-guide/step-operators/sagemaker.md) supports passing in [`estimator_args`](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-aws/#zenml.integrations.aws.flavors.sagemaker\_step\_operator\_flavor.SagemakerStepOperatorSettings). The way to specify this would be to use the key `step_operator` ```python @step(step_operator="nameofstepoperator", settings= {"step_operator": {"estimator_args": {"instance_type": "m7g.medium"}}}) def my_step(): ... # Using the class @step(step_operator="nameofstepoperator", settings= {"step_operator": SagemakerStepOperatorSettings(instance_type="m7g.medium")}) def my_step(): ... ``` or in YAML: ```yaml steps: my_step: step_operator: "nameofstepoperator" settings: step_operator: estimator_args: instance_type: m7g.medium ```
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/use-configuration-files/what-can-be-configured.md ================ # What can be configured Here is an example of a sample YAML file, with the most important configuration highlighted. For brevity, we have removed all possible keys. To view a sample file with all possible keys, refer to [this page](./autogenerate-a-template-yaml-file.md). ```yaml # Build ID (i.e. which Docker image to use) build: dcd6fafb-c200-4e85-8328-428bef98d804 # Enable flags (boolean flags that control behavior) enable_artifact_metadata: True enable_artifact_visualization: False enable_cache: False enable_step_logs: True # Extra dictionary to pass in arbitrary values extra: any_param: 1 another_random_key: "some_string" # Specify the "ZenML Model" model: name: "classification_model" version: production audience: "Data scientists" description: "This classifies hotdogs and not hotdogs" ethics: "No ethical implications" license: "Apache 2.0" limitations: "Only works for hotdogs" tags: ["sklearn", "hotdog", "classification"] # Parameters of the pipeline parameters: dataset_name: "another_dataset" # Name of the run run_name: "my_great_run" # Schedule, if supported on the orchestrator schedule: catchup: true cron_expression: "* * * * *" # Real-time settings for Docker and resources settings: # Controls Docker building docker: apt_packages: ["curl"] copy_files: True dockerfile: "Dockerfile" dockerignore: ".dockerignore" environment: ZENML_LOGGING_VERBOSITY: DEBUG parent_image: "zenml-io/zenml-cuda" requirements: ["torch"] skip_build: False # Control resources for the entire pipeline resources: cpu_count: 2 gpu_count: 1 memory: "4Gb" # Per step configuration steps: # Top-level key should be the name of the step invocation ID train_model: # Parameters of the step parameters: data_source: "best_dataset" # Step-only configuration experiment_tracker: "mlflow_production" step_operator: "vertex_gpu" outputs: {} failure_hook_source: {} success_hook_source: {} # Same as pipeline level configuration, if specified overrides for this step enable_artifact_metadata: True enable_artifact_visualization: True enable_cache: False enable_step_logs: True # Same as pipeline level configuration, if specified overrides for this step extra: {} # Same as pipeline level configuration, if specified overrides for this step model: {} # Same as pipeline level configuration, if specified overrides for this step settings: docker: {} resources: {} # Stack component specific settings step_operator.sagemaker: estimator_args: instance_type: m7g.medium ``` ## Deep-dive ### `enable_XXX` parameters These are boolean flags for various configurations: * `enable_artifact_metadata`: Whether to [associate metadata with artifacts or not](../../data-artifact-management/handle-data-artifacts/handle-custom-data-types.md#optional-which-metadata-to-extract-for-the-artifact). * `enable_artifact_visualization`: Whether to [attach visualizations of artifacts](../../data-artifact-management/visualize-artifacts/README.md). * `enable_cache`: Utilize [caching](../build-pipelines/control-caching-behavior.md) or not. * `enable_step_logs`: Enable tracking [step logs](../../control-logging/enable-or-disable-logs-storing.md). ```yaml enable_artifact_metadata: True enable_artifact_visualization: True enable_cache: True enable_step_logs: True ``` ### `build` ID The UUID of the [`build`](../../../how-to/customize-docker-builds/README.md) to use for this pipeline. If specified, Docker image building is skipped for remote orchestrators, and the Docker image specified in this build is used. ```yaml build: ``` ### Configuring the `model` Specifies the ZenML [Model](../../../user-guide/starter-guide/track-ml-models.md) to use for this pipeline. ```yaml model: name: "ModelName" version: "production" description: An example model tags: ["classifier"] ``` ### Pipeline and step `parameters` A dictionary of JSON-serializable [parameters](../../pipeline-development/build-pipelines/use-pipeline-step-parameters.md) specified at the pipeline or step level. For example: ```yaml parameters: gamma: 0.01 steps: trainer: parameters: gamma: 0.001 ``` Corresponds to: ```python from zenml import step, pipeline @step def trainer(gamma: float): # Use gamma as normal print(gamma) @pipeline def my_pipeline(gamma: float): # use gamma or pass it into the step print(0.01) trainer(gamma=gamma) ``` Important note, in the above case, the value of the step would be the one defined in the `steps` key (i.e. 0.001). So the YAML config always takes precedence over pipeline parameters that are passed down to steps in code. Read [this section for more details](configuration-hierarchy.md). Normally, parameters defined at the pipeline level are used in multiple steps, and then no step-level configuration is defined. {% hint style="info" %} Note that `parameters` are different from `artifacts`. Parameters are JSON-serializable values that are passed in the runtime configuration of a pipeline. Artifacts are inputs and outputs of a step, and need not always be JSON-serializable ([materializers](../../data-artifact-management/handle-data-artifacts/handle-custom-data-types.md) handle their persistence in the [artifact store](../../../component-guide/artifact-stores/artifact-stores.md)). {% endhint %} ### Setting the `run_name` To change the name for a run, pass `run_name` as a parameter. This can be a dynamic value as well. ```python run_name: ``` {% hint style="warning" %} You will not be able to run with the same run\_name twice. Do not set this statically when running on a schedule. Try to include some auto-incrementation or timestamp to the name. {% endhint %} ### Stack Component Runtime settings Settings are special runtime configurations of a pipeline or a step that require a [dedicated section](runtime-configuration.md). In short, they define a bunch of execution configuration such as Docker building and resource settings. ### Docker Settings Docker Settings can be passed in directly as objects, or a dictionary representation of the object. For example, the Docker configuration can be set in configuration files as follows: ```yaml settings: docker: requirements: - pandas ``` {% hint style="info" %} Find a complete list of all Docker Settings [here](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-config/#zenml.config.docker\_settings.DockerSettings). To learn more about pipeline containerization consult our documentation on this [here](../../../how-to/customize-docker-builds/README.md). {% endhint %} ### Resource Settings Some stacks allow setting the resource settings using these settings. ```yaml resources: cpu_count: 2 gpu_count: 1 memory: "4Gb" ``` Note that this may not work for all types of stack components. To learn which components support this, please refer to the specific orchestrator docs. ### `failure_hook_source` and `success_hook_source` The `source` of the [failure and success hooks](../../pipeline-development/build-pipelines/use-failure-success-hooks.md) can be specified. ### Step-specific configuration A lot of pipeline-level configuration can also be applied at a step level (as we have already seen with the `enable_cache` flag). However, there is some configuration that is step-specific, meaning it cannot be applied at a pipeline level, but only at a step level. * `experiment_tracker`: Name of the [experiment\_tracker](../../../component-guide/experiment-trackers/experiment-trackers.md) to enable for this step. This experiment\_tracker should be defined in the active stack with the same name. * `step_operator`: Name of the [step\_operator](../../../component-guide/step-operators/step-operators.md) to enable for this step. This step\_operator should be defined in the active stack with the same name. * `outputs`: This is configuration of the output artifacts of this step. This is further keyed by output name (by default, step outputs [are named `output`](../../data-artifact-management/handle-data-artifacts/return-multiple-outputs-from-a-step.md)). The most interesting configuration here is the `materializer_source`, which is the UDF path of the materializer in code to use for this output (e.g. `materializers.some_data.materializer.materializer_class`). Read more about this source path [here](../../data-artifact-management/handle-data-artifacts/handle-custom-data-types.md).
ZenML Scarf
================ File: docs/book/how-to/pipeline-development/README.md ================ --- icon: paintbrush-pencil --- # Pipeline Development This section covers all aspects of pipeline development in ZenML. ================ File: docs/book/how-to/popular-integrations/aws-guide.md ================ --- description: A simple guide to create an AWS stack to run your ZenML pipelines --- # Run on AWS This page aims to quickly set up a minimal production stack on AWS. With just a few simple steps, you will set up an IAM role with specifically-scoped permissions that ZenML can use to authenticate with the relevant AWS resources. {% hint style="info" %} Would you like to skip ahead and deploy a full AWS ZenML cloud stack already? 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. {% endhint %} ## 1) Set up credentials and local environment To follow this guide, you need: * An active AWS account with necessary permissions for AWS S3, SageMaker, ECR, and ECS. * ZenML [installed](../../getting-started/installation.md) * AWS CLI installed and configured with your AWS credentials. You can follow the instructions [here](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html). Once ready, navigate to the AWS console: 1. Choose an AWS region In the AWS console, choose the region where you want to deploy your ZenML stack resources. Make note of the region name (e.g., `us-east-1`, `eu-west-2`, etc.) as you will need it in subsequent steps. 2. Create an IAM role For this, you'll need to find out your AWS account ID. You can find this by running: ```shell aws sts get-caller-identity --query Account --output text ``` This will output your AWS account ID. Make a note of this as you will need it in the next steps. (If you're doing anything more esoteric with your AWS account and IAM roles, this might not work for you. The account ID here that we're trying to get is the root account ID that you use to log in to the AWS console.) Then create a file named `assume-role-policy.json` with the following content: ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam:::root", "Service": "sagemaker.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } ``` Make sure to replace the placeholder `` with your actual AWS account ID that we found earlier. Now create a new IAM role that ZenML will use to access AWS resources. We'll use `zenml-role` as a role name in this example, but you can feel free to choose something else if you prefer. Run the following command to create the role: ```shell aws iam create-role --role-name zenml-role --assume-role-policy-document file://assume-role-policy.json ``` Be sure to take note of the information that is output to the terminal, as you will need it in the next steps, especially the Role ARN. 1. Attach policies to the role Attach the following policies to the role to grant access to the necessary AWS services: * `AmazonS3FullAccess` * `AmazonEC2ContainerRegistryFullAccess` * `AmazonSageMakerFullAccess` ```shell aws iam attach-role-policy --role-name zenml-role --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess aws iam attach-role-policy --role-name zenml-role --policy-arn arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryFullAccess aws iam attach-role-policy --role-name zenml-role --policy-arn arn:aws:iam::aws:policy/AmazonSageMakerFullAccess ``` 1. If you have not already, install the AWS and S3 ZenML integrations: ```shell zenml integration install aws s3 -y ``` ## 2) Create a Service Connector within ZenML Create an AWS Service Connector within ZenML. The service connector will allow ZenML and other ZenML components to authenticate themselves with AWS using the IAM role. {% tabs %} {% tab title="CLI" %} ```shell zenml service-connector register aws_connector \ --type aws \ --auth-method iam-role \ --role_arn= \ --region= \ --aws_access_key_id= \ --aws_secret_access_key= ``` Replace `` with the ARN of the IAM role you created in the previous step, `` with the respective value and use your AWS access key ID and secret access key that we noted down earlier. {% endtab %} {% endtabs %} ## 3) Create Stack Components ### Artifact Store (S3) An [artifact store](../../user-guide/production-guide/remote-storage.md) is used for storing and versioning data flowing through your pipelines. 1. Before you run anything within the ZenML CLI, create an AWS S3 bucket. If you already have one, you can skip this step. (Note: the bucket name should be unique, so you might need to try a few times to find a unique name.) ```shell aws s3api create-bucket --bucket your-bucket-name ``` Once this is done, you can create the ZenML stack component as follows: 1. Register an S3 Artifact Store with the connector ```shell zenml artifact-store register cloud_artifact_store -f s3 --path=s3://bucket-name --connector aws_connector ``` More details [here](../../component-guide/artifact-stores/s3.md). ### Orchestrator (SageMaker Pipelines) An [orchestrator](../../user-guide/production-guide/cloud-orchestration.md) is the compute backend to run your pipelines. 1. Before you run anything within the ZenML CLI, head on over to AWS and create a SageMaker domain (Skip this if you already have one). The instructions for creating a domain can be found [in the AWS core documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/onboard-quick-start.html). A SageMaker domain is a central management unit for all SageMaker users and resources within a region. It provides a single sign-on (SSO) experience and enables users to create and manage SageMaker resources, such as notebooks, training jobs, and endpoints, within a collaborative environment. When you create a SageMaker domain, you specify the configuration settings, such as the domain name, user profiles, and security settings. Each user within a domain gets their own isolated workspace, which includes a JupyterLab interface, a set of compute resources, and persistent storage. The SageMaker orchestrator in ZenML requires a SageMaker domain to run pipelines because it leverages the SageMaker Pipelines service, which is part of the SageMaker ecosystem. SageMaker Pipelines allows you to define, execute, and manage end-to-end machine learning workflows using a declarative approach. By creating a SageMaker domain, you establish the necessary environment and permissions for the SageMaker orchestrator to interact with SageMaker Pipelines and other SageMaker resources seamlessly. The domain acts as a prerequisite for using the SageMaker orchestrator in ZenML. Once this is done, you can create the ZenML stack component as follows: 1. Register a SageMaker Pipelines orchestrator stack component: You'll need the IAM role ARN that we noted down earlier to register the orchestrator. This is the 'execution role' ARN you need to pass to the orchestrator. ```shell zenml orchestrator register sagemaker-orchestrator --flavor=sagemaker --region= --execution_role= ``` **Note**: The SageMaker orchestrator utilizes the AWS configuration for operation and does not require direct connection via a service connector for authentication, as it relies on your AWS CLI configurations or environment variables. More details [here](../../component-guide/orchestrators/sagemaker.md). ### Container Registry (ECR) A [container registry](../../component-guide/container-registries/container-registries.md) is used to store Docker images for your pipelines. 1. You'll need to create a repository in ECR. If you already have one, you can skip this step. ```shell aws ecr create-repository --repository-name zenml --region ``` Once this is done, you can create the ZenML stack component as follows: 1. Register an ECR container registry stack component: ```shell zenml container-registry register ecr-registry --flavor=aws --uri=.dkr.ecr..amazonaws.com --connector aws-connector ``` More details [here](../../component-guide/container-registries/aws.md). ## 4) Create stack {% tabs %} {% tab title="CLI" %} ```shell export STACK_NAME=aws_stack zenml stack register ${STACK_NAME} -o ${ORCHESTRATOR_NAME} \ -a ${ARTIFACT_STORE_NAME} -c ${CONTAINER_REGISTRY_NAME} --set ``` {% hint style="info" %} In case you want to also add any other stack components to this stack, feel free to do so. {% endhint %} {% endtab %} {% tab title="Dashboard" %}

Combine the three stack components and you have your AWS stack. Feel free to add any other component of your choice as well.

{% endtab %} {% endtabs %} ## 5) And you're already done! Just like that, you now have a fully working AWS stack ready to go. Feel free to take it for a spin by running a pipeline on it. Define a ZenML pipeline: ```python from zenml import pipeline, step @step def hello_world() -> str: return "Hello from SageMaker!" @pipeline def aws_sagemaker_pipeline(): hello_world() if __name__ == "__main__": aws_sagemaker_pipeline() ``` Save this code to run.py and execute it. The pipeline will use AWS S3 for artifact storage, Amazon SageMaker Pipelines for orchestration, and Amazon ECR for container registry. ```shell python run.py ```

Sequence of events that happen when running a pipeline on a remote stack with a code repository

Read more in the [production guide](../../user-guide/production-guide/README.md). ## Cleanup {% hint style="warning" %} Make sure you no longer need the resources before deleting them. The instructions and commands that follow are DESTRUCTIVE. {% endhint %} Delete any AWS resources you no longer use to avoid additional charges. You'll want to do the following: ```shell # delete the S3 bucket aws s3 rm s3://your-bucket-name --recursive aws s3api delete-bucket --bucket your-bucket-name # delete the SageMaker domain aws sagemaker delete-domain --domain-id # delete the ECR repository aws ecr delete-repository --repository-name zenml-repository --force # detach policies from the IAM role aws iam detach-role-policy --role-name zenml-role --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess aws iam detach-role-policy --role-name zenml-role --policy-arn arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryFullAccess aws iam detach-role-policy --role-name zenml-role --policy-arn arn:aws:iam::aws:policy/AmazonSageMakerFullAccess # delete the IAM role aws iam delete-role --role-name zenml-role ``` Make sure to run these commands in the same AWS region where you created the resources. By running these cleanup commands, you will delete the S3 bucket, SageMaker domain, ECR repository, and IAM role, along with their associated policies. This will help you avoid any unnecessary charges for resources you no longer need. Remember to be cautious when deleting resources and ensure that you no longer require them before running the deletion commands. ## Conclusion In this guide, we walked through the process of setting up an AWS stack with ZenML to run your machine learning pipelines in a scalable and production-ready environment. The key steps included: 1. Setting up credentials and the local environment by creating an IAM role with the necessary permissions. 2. Creating a ZenML service connector to authenticate with AWS services using the IAM role. 3. Configuring stack components, including an S3 artifact store, a SageMaker Pipelines orchestrator, and an ECR container registry. 4. Registering the stack components and creating a ZenML stack. By following these steps, you can leverage the power of AWS services, such as S3 for artifact storage, SageMaker Pipelines for orchestration, and ECR for container management, all within the ZenML framework. This setup allows you to build, deploy, and manage machine learning pipelines efficiently and scale your workloads based on your requirements. The benefits of using an AWS stack with ZenML include: * Scalability: Leverage the scalability of AWS services to handle large-scale machine learning workloads. * Reproducibility: Ensure reproducibility of your pipelines with versioned artifacts and containerized environments. * Collaboration: Enable collaboration among team members by using a centralized stack and shared resources. * Flexibility: Customize and extend your stack components based on your specific needs and preferences. Now that you have a functional AWS stack set up with ZenML, you can explore more advanced features and capabilities offered by ZenML. Some next steps to consider: * Dive deeper into ZenML's [production guide](../../user-guide/production-guide/README.md) to learn best practices for deploying and managing production-ready pipelines. * Explore ZenML's [integrations](../../component-guide/README.md) with other popular tools and frameworks in the machine learning ecosystem. * Join the [ZenML community](https://zenml.io/slack) to connect with other users, ask questions, and get support. By leveraging the power of AWS and ZenML, you can streamline your machine learning workflows, improve collaboration, and deploy production-ready pipelines with ease. What follows is a set of best practices for using your AWS stack with ZenML. ## Best Practices for Using an AWS Stack with ZenML When working with an AWS stack in ZenML, consider the following best practices to optimize your workflow, enhance security, and improve cost-efficiency. These are all things you might want to do or amend in your own setup once you have tried running some pipelines on your AWS stack. ### Use IAM Roles and Least Privilege Principle Always adhere to the principle of least privilege when setting up IAM roles. Only grant the minimum permissions necessary for your ZenML pipelines to function. Regularly review and audit your [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) to ensure they remain appropriate and secure. ### Leverage AWS Resource Tagging Implement a [consistent tagging strategy](https://aws.amazon.com/solutions/guidance/tagging-on-aws/) for all of your AWS resources that you use for your pipelines. For example, if you have S3 as an artifact store in your stack, you should tag it like shown below: ```shell aws s3api put-bucket-tagging --bucket your-bucket-name --tagging 'TagSet=[{Key=Project,Value=ZenML},{Key=Environment,Value=Production}]' ``` These tags will help you with billing and cost allocation tracking and also with any cleanup efforts. ### Implement Cost Management Strategies Use [AWS Cost Explorer](https://aws.amazon.com/aws-cost-management/aws-cost-explorer/) and [AWS Budgets](https://aws.amazon.com/aws-cost-management/aws-budgets/) to monitor and manage your spending. To create a cost budget: 1. Create a JSON file (e.g., `budget-config.json`) defining the budget: ```json { "BudgetLimit": { "Amount": "100", "Unit": "USD" }, "BudgetName": "ZenML Monthly Budget", "BudgetType": "COST", "CostFilters": { "TagKeyValue": [ "user:Project$ZenML" ] }, "CostTypes": { "IncludeTax": true, "IncludeSubscription": true, "UseBlended": false }, "TimeUnit": "MONTHLY" } ``` 2. Create the cost budget: ```shell aws budgets create-budget --account-id your-account-id --budget file://budget-config.json ``` Set up cost allocation tags to track expenses related to your ZenML projects: ```shell aws ce create-cost-category-definition --name ZenML-Projects --rules-version 1 --rules file://rules.json ``` ### Use Warm Pools for your SageMaker Pipelines [Warm Pools in SageMaker](../../component-guide/orchestrators/sagemaker.md#using-warm-pools-for-your-pipelines) 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` 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. ### Implement a Robust Backup Strategy Regularly backup your critical data and configurations. For S3, enable versioning and consider using [cross-region replication](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html) for disaster recovery. By following these best practices and implementing the provided examples, you can create a more secure, efficient, and cost-effective AWS stack for your ZenML projects. Remember to regularly review and update your practices as your projects evolve and as AWS introduces new features and services.
ZenML Scarf
================ File: docs/book/how-to/popular-integrations/azure-guide.md ================ --- description: A simple guide to create an Azure stack to run your ZenML pipelines --- # Run on Azure This page aims to quickly set up a minimal production stack on Azure. With just a few simple steps, you will set up a resource group, a service principal with correct permissions and the relevant ZenML stack and components. {% hint style="info" %} Would you like to skip ahead and deploy a full Azure ZenML cloud stack already? 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. {% endhint %} To follow this guide, you need: * An active Azure account. * ZenML [installed](../../getting-started/installation.md). * ZenML `azure` integration installed with `zenml integration install azure`. ## 1. Set up proper credentials You can start by [creating a service principal by creating an app registration](https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/manage-azureml-service/authentication-in-azureml/authentication-in-azureml.ipynb) on Azure: 1. Go to the App Registrations on the Azure portal. 2. Click on `+ New registration`, 3. Give it a name and click register. ![Azure App Registrations](../../.gitbook/assets/azure_1.png) ![Azure App Registrations](../../.gitbook/assets/azure_2.png) Once you create the service principal, you will get an Application ID and Tenant ID as they will be needed later. Next, go to your service principal and click on the `Certificates & secrets` in the `Manage` menu. Here, you have to create a client secret. Note down the secret value as it will be needed later. ![Azure App Registrations](../../.gitbook/assets/azure_3.png) ## 2. Create a resource group and the AzureML instance Now, you have to [create a resource group on Azure](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-portal). To do this, go to the Azure portal and go to the `Resource Groups` page and click `+ Create`. ![Azure Resource Groups](../../.gitbook/assets/azure_4.png) Once the resource group is created, go to the overview page of your new resource group and click `+ Create`. This will open up the marketplace where you can select a variety of resource to create. Look for `Azure Machine Learning`. ![Azure Role Assignments](../../.gitbook/assets/azure_5.png) Select it, and you will start the process of creating an AzureML workspace. As you can see from the `Workspace details`, AzureML workspaces come equipped with a storage account, key vault, and application insights. It is highly recommended that you create a container registry as well. ![Azure Role Assignments](../../.gitbook/assets/azure_6.png) ## 3. Create the required role assignments Now, that you have your app registration and the resources, you have to create the corresponding role assignments. In order to do this, go to your resource group, open up `Access control (IAM)` on the left side and `+Add` a new role assignment. ![Azure Resource Groups](../../.gitbook/assets/azure-role-assignment-1.png) In the role assignment page, search for AzureML which will show you a list of roles defined with the scope of AzureML workspaces. ![Azure Resource Groups](../../.gitbook/assets/azure-role-assignment-2.png) One by one, you have to select `AzureML Compute Operator`, `AzureML Data Scientist`, and `AzureML Registry User` and click `Next`. ![Azure Resource Groups](../../.gitbook/assets/azure-role-assignment-3.png) Finally, click `+Select Members`, search for your registered app by its ID, and assign the role accordingly. ## 4. Create a service connector Now you have everything set up, you can go ahead and create [a ZenML Azure Service Connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md). ```bash zenml service-connector register azure_connector --type azure \ --auth-method service-principal \ --client_secret= \ --tenant_id= \ --client_id= ``` You will use this service connector later on to connect your components with proper authentication. ## 5. Create Stack Components In order to run any workflows on Azure using ZenML, you need an artifact store, an orchestrator and a container registry. ### Artifact Store (Azure Blob Storage) For the artifact store, we will be using the storage account attached to our AzureML workspace. But before registering the component itself, you have to create a container for blob storage. To do this, go to the corresponding storage account in your workspace and create a new container: ![Azure Blob Storage](../../.gitbook/assets/azure_7.png) Once you create the container, you can go ahead, register your artifact store using its path and connect it to your service connector: ```bash zenml artifact-store register azure_artifact_store -f azure \ --path= \ --connector azure_connector ``` For more information regarding Azure Blob Storage artifact stores, feel free to [check the docs](../../component-guide/artifact-stores/azure.md). ### Orchestrator (AzureML) As for the orchestrator, no additional setup is needed. Simply use the following command to register it and connect it your service connector: ```bash zenml orchestrator register azure_orchestrator -f azureml \ --subscription_id= \ --resource_group= \ --workspace= \ --connector azure_connector ``` For more information regarding AzureML orchestrator, feel free to [check the docs](../../component-guide/orchestrators/azureml.md). ### Container Registry (Azure Container Registry) Similar to the orchestrator, you can register and connect your container registry using the following command: ```bash zenml container-registry register azure_container_registry -f azure \ --uri= \ --connector azure_connector ``` For more information regarding Azure container registries, feel free to [check the docs](../../component-guide/container-registries/azure.md). ## 6. Create a Stack Now, you can use the registered components to create an Azure ZenML stack: ```shell zenml stack register azure_stack \ -o azure_orchestrator \ -a azure_artifact_store \ -c azure_container_registry \ --set ``` ## 7. ...and you are done. Just like that, you now have a fully working Azure stack ready to go. Feel free to take it for a spin by running a pipeline on it. Define a ZenML pipeline: ```python from zenml import pipeline, step @step def hello_world() -> str: return "Hello from Azure!" @pipeline def azure_pipeline(): hello_world() if __name__ == "__main__": azure_pipeline() ``` Save this code to run.py and execute it. The pipeline will use Azure Blob Storage for artifact storage, AzureML for orchestration, and an Azure container registry. ```shell python run.py ``` Now that you have a functional Azure stack set up with ZenML, you can explore more advanced features and capabilities offered by ZenML. Some next steps to consider: * Dive deeper into ZenML's [production guide](../../user-guide/production-guide/README.md) to learn best practices for deploying and managing production-ready pipelines. * Explore ZenML's [integrations](../../component-guide/README.md) with other popular tools and frameworks in the machine learning ecosystem. * Join the [ZenML community](https://zenml.io/slack) to connect with other users, ask questions, and get support.
ZenML Scarf
================ File: docs/book/how-to/popular-integrations/gcp-guide.md ================ --- description: A simple guide to quickly set up a minimal stack on GCP. --- # Set up a minimal GCP stack This page aims to quickly set up a minimal production stack on GCP. With just a few simple steps you will set up a service account with specifically-scoped permissions that ZenML can use to authenticate with the relevant GCP resources. {% hint style="info" %} Would you like to skip ahead and deploy a full GCP ZenML cloud stack already? 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. {% endhint %} {% hint style="warning" %} While this guide focuses on Google Cloud, we are seeking contributors to create a similar guide for other cloud providers. If you are interested, please create a [pull request over on GitHub](https://github.com/zenml-io/zenml/blob/main/CONTRIBUTING.md). {% endhint %} ### 1) Choose a GCP project In the Google Cloud console, on the project selector page, select or [create a Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects). Make sure a billing account is attached to this project to allow the use of some APIs. This is how you would do it from the CLI if this is preferred. ```bash gcloud projects create --billing-project= ``` {% hint style="info" %} If you don't plan to keep the resources that you create in this procedure, create a new project. After you finish these steps, you can delete the project, thereby removing all resources associated with the project. {% endhint %} ### 2) Enable GCloud APIs The [following APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com,artifactregistry.googleapis.com,run.googleapis.com,logging.googleapis.com\\\&redirect=https://cloud.google.com/functions/docs/create-deploy-gcloud&\\\_ga=2.103703808.1862683951.1694002459-205697788.1651483076&\\\_gac=1.161946062.1694011263.Cj0KCQjwxuCnBhDLARIsAB-cq1ouJZlVKAVPMsXnYrgQVF2t1Q2hUjgiHVpHXi2N0NlJvG3j3y-PPh8aAoSIEALw\\\_wcB) will need to be enabled within your chosen GCP project. * Cloud Functions API # For the vertex orchestrator * Cloud Run Admin API # For the vertex orchestrator * Cloud Build API # For the container registry * Artifact Registry API # For the container registry * Cloud Logging API # Generally needed ### 3) Create a dedicated service account The service account should have these following roles. * AI Platform Service Agent * Storage Object Admin These roles give permissions for full CRUD on storage objects and full permissions for compute within VertexAI. ### 4) Create a JSON Key for your service account This [json file](https://cloud.google.com/iam/docs/keys-create-delete) will allow the service account to assume the identity of this service account. You will need the filepath of the downloaded file in the next step. ```bash export JSON_KEY_FILE_PATH= ``` ### 5) Create a Service Connector within ZenML The service connector will allow ZenML and other ZenML components to authenticate themselves with GCP. {% tabs %} {% tab title="CLI" %} ```bash zenml integration install gcp \ && zenml service-connector register gcp_connector \ --type gcp \ --auth-method service-account \ --service_account_json=@${JSON_KEY_FILE_PATH} \ --project_id= ``` {% endtab %} {% endtabs %} ### 6) Create Stack Components #### Artifact Store Before you run anything within the ZenML CLI, head on over to GCP and create a GCS bucket, in case you don't already have one that you can use. Once this is done, you can create the ZenML stack component as follows: {% tabs %} {% tab title="CLI" %} ```bash export ARTIFACT_STORE_NAME=gcp_artifact_store # Register the GCS artifact-store and reference the target GCS bucket zenml artifact-store register ${ARTIFACT_STORE_NAME} --flavor gcp \ --path=gs:// # Connect the GCS artifact-store to the target bucket via a GCP Service Connector zenml artifact-store connect ${ARTIFACT_STORE_NAME} -i ``` {% hint style="info" %} Head on over to our [docs](../../component-guide/artifact-stores/gcp.md) to learn more about artifact stores and how to configure them. {% endhint %} {% endtab %} {% endtabs %} #### Orchestrator This guide will use Vertex AI as the orchestrator to run the pipelines. As a serverless service Vertex is a great choice for quick prototyping of your MLOps stack. The orchestrator can be switched out at any point in the future for a more use-case- and budget-appropriate solution. {% tabs %} {% tab title="CLI" %} ```bash export ORCHESTRATOR_NAME=gcp_vertex_orchestrator # Register the GCS artifact-store and reference the target GCS bucket zenml orchestrator register ${ORCHESTRATOR_NAME} --flavor=vertex --project= --location=europe-west2 # Connect the GCS orchestrator to the target gcp project via a GCP Service Connector zenml orchestrator connect ${ORCHESTRATOR_NAME} -i ``` {% hint style="info" %} Head on over to our [docs](../../component-guide/orchestrators/vertex.md) to learn more about orchestrators and how to configure them. {% endhint %} {% endtab %} {% endtabs %} #### Container Registry {% tabs %} {% tab title="CLI" %} ```bash export CONTAINER_REGISTRY_NAME=gcp_container_registry zenml container-registry register ${CONTAINER_REGISTRY_NAME} --flavor=gcp --uri= # Connect the GCS orchestrator to the target gcp project via a GCP Service Connector zenml container-registry connect ${CONTAINER_REGISTRY_NAME} -i ``` {% hint style="info" %} Head on over to our [docs](../../component-guide/container-registries/container-registries.md) to learn more about container registries and how to configure them. {% endhint %} {% endtab %} {% endtabs %} ### 7) Create Stack {% tabs %} {% tab title="CLI" %} ```bash export STACK_NAME=gcp_stack zenml stack register ${STACK_NAME} -o ${ORCHESTRATOR_NAME} \ -a ${ARTIFACT_STORE_NAME} -c ${CONTAINER_REGISTRY_NAME} --set ``` {% hint style="info" %} In case you want to also add any other stack components to this stack, feel free to do so. {% endhint %} {% endtab %} {% endtabs %} ## And you're already done! Just like that, you now have a fully working GCP stack ready to go. Feel free to take it for a spin by running a pipeline on it. ## Cleanup If you do not want to use any of the created resources in the future, simply delete the project you created. ```bash gcloud project delete ``` ## Best Practices for Using a GCP Stack with ZenML When working with a GCP stack in ZenML, consider the following best practices to optimize your workflow, enhance security, and improve cost-efficiency. These are all things you might want to do or amend in your own setup once you have tried running some pipelines on your GCP stack. ### Use IAM and Least Privilege Principle Always adhere to the principle of least privilege when setting up IAM roles. Only grant the minimum permissions necessary for your ZenML pipelines to function. Regularly review and audit your IAM roles to ensure they remain appropriate and secure. ### Leverage GCP Resource Labeling Implement a consistent labeling strategy for your GCP resources. To label a GCS bucket, for example: ```shell gcloud storage buckets update gs://your-bucket-name --update-labels=project=zenml,environment=production ``` This command adds two labels to the bucket: - A label with key "project" and value "zenml" - A label with key "environment" and value "production" You can add or update multiple labels in a single command by separating them with commas. To remove a label, set its value to null: ```shell gcloud storage buckets update gs://your-bucket-name --update-labels=label-to-remove=null ``` These labels will help you with billing and cost allocation tracking and also with any cleanup efforts. To view the labels on a bucket: ```shell gcloud storage buckets describe gs://your-bucket-name --format="default(labels)" ``` This will display all labels currently set on the specified bucket. ### Implement Cost Management Strategies Use Google Cloud's [Cost Management tools](https://cloud.google.com/docs/costs-usage) to monitor and manage your spending. To set up a budget alert: 1. Navigate to the Google Cloud Console 2. Go to Billing > Budgets & Alerts 3. Click "Create Budget" 4. Set your budget amount, scope (project, product, etc.), and alert thresholds You can also use the `gcloud` CLI to create a budget: ```shell gcloud billing budgets create --billing-account=BILLING_ACCOUNT_ID --display-name="ZenML Monthly Budget" --budget-amount=1000 --threshold-rule=percent=90 ``` Set up cost allocation labels to track expenses related to your ZenML projects in the Google Cloud Billing Console. ### Implement a Robust Backup Strategy Regularly backup your critical data and configurations. For GCS, for example, enable versioning and consider using cross-region replication for disaster recovery. To enable versioning on a GCS bucket: ```shell gsutil versioning set on gs://your-bucket-name ``` To set up cross-region replication: ```shell gsutil rewrite -r gs://source-bucket gs://destination-bucket ``` By following these best practices and implementing the provided examples, you can create a more secure, efficient, and cost-effective GCP stack for your ZenML projects. Remember to regularly review and update your practices as your projects evolve and as GCP introduces new features and services.
ZenML Scarf
================ File: docs/book/how-to/popular-integrations/kubeflow.md ================ --- description: Run your ML pipelines on Kubeflow Pipelines. --- # Kubeflow The ZenML Kubeflow Orchestrator allows you to run your ML pipelines on Kubeflow Pipelines without writing Kubeflow code. ## Prerequisites To use the Kubeflow Orchestrator, you'll need: - ZenML `kubeflow` integration installed (`zenml integration install kubeflow`) - Docker installed and running - `kubectl` installed (optional, see below) - A Kubernetes cluster with Kubeflow Pipelines installed (see deployment guide for your cloud provider) - A remote artifact store and container registry in your ZenML stack - A remote ZenML server deployed to the cloud - The name of your Kubernetes context pointing to the remote cluster (optional, see below) ## Configuring the Orchestrator There are two ways to configure the orchestrator: 1. Using a [Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) to connect to the remote cluster (recommended for cloud-managed clusters). No local `kubectl` context needed. ```bash zenml orchestrator register --flavor kubeflow zenml service-connector list-resources --resource-type kubernetes-cluster -e zenml orchestrator connect --connector zenml stack update -o ``` 2. Configuring `kubectl` with a context pointing to the remote cluster and setting `kubernetes_context` in the orchestrator config: ```bash zenml orchestrator register \ --flavor=kubeflow \ --kubernetes_context= zenml stack update -o ``` ## Running a Pipeline Once configured, you can run any ZenML pipeline using the Kubeflow Orchestrator: ```python python your_pipeline.py ``` This will create a Kubernetes pod for each step in your pipeline. You can view pipeline runs in the Kubeflow UI. ## Additional Configuration You can further configure the orchestrator using `KubeflowOrchestratorSettings`: ```python from zenml.integrations.kubeflow.flavors.kubeflow_orchestrator_flavor import KubeflowOrchestratorSettings kubeflow_settings = KubeflowOrchestratorSettings( client_args={}, user_namespace="my_namespace", pod_settings={ "affinity": {...}, "tolerations": [...] } ) @pipeline( settings={ "orchestrator": kubeflow_settings } ) ``` This allows specifying client arguments, user namespace, pod affinity/tolerations, and more. ## Multi-Tenancy Deployments For multi-tenant Kubeflow deployments, specify the `kubeflow_hostname` ending in `/pipeline` when registering the orchestrator: ```bash zenml orchestrator register \ --flavor=kubeflow \ --kubeflow_hostname= # e.g. https://mykubeflow.example.com/pipeline ``` And provide the namespace, username and password in the orchestrator settings: ```python kubeflow_settings = KubeflowOrchestratorSettings( client_username="admin", client_password="abc123", user_namespace="namespace_name" ) @pipeline( settings={ "orchestrator": kubeflow_settings } ) ``` For more advanced options and details, refer to the [full Kubeflow Orchestrator documentation](../../component-guide/orchestrators/kubeflow.md).
ZenML Scarf
================ File: docs/book/how-to/popular-integrations/kubernetes.md ================ --- description: Learn how to deploy ZenML pipelines on a Kubernetes cluster. --- # Kubernetes The ZenML Kubernetes Orchestrator allows you to run your ML pipelines on a Kubernetes cluster without writing Kubernetes code. It's a lightweight alternative to more complex orchestrators like Airflow or Kubeflow. {% hint style="info" %} If you only want to run individual steps of your pipeline in Kubernetes, check out our [Kubernetes Step Operator](../../component-guide/step-operators/kubernetes.md). {% endhint %} ## Prerequisites To use the Kubernetes Orchestrator, you'll need: - ZenML `kubernetes` integration installed (`zenml integration install kubernetes`) - Docker installed and running - `kubectl` installed - A remote artifact store and container registry in your ZenML stack - A deployed Kubernetes cluster - A configured `kubectl` context pointing to the cluster (optional, see below) ## Deploying the Orchestrator 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 cloud guide](../../user-guide/cloud-guide/cloud-guide.md). ## Configuring the Orchestrator There are two ways to configure the orchestrator: 1. Using a [Service Connector](../../how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) to connect to the remote cluster. This is the recommended approach, especially for cloud-managed clusters. No local `kubectl` context is needed. ```bash zenml orchestrator register --flavor kubernetes zenml service-connector list-resources --resource-type kubernetes-cluster -e zenml orchestrator connect --connector zenml stack register -o ... --set ``` 2. Configuring `kubectl` with a context pointing to the remote cluster and setting the `kubernetes_context` in the orchestrator config: ```bash zenml orchestrator register \ --flavor=kubernetes \ --kubernetes_context= zenml stack register -o ... --set ``` ## Running a Pipeline Once configured, you can run any ZenML pipeline using the Kubernetes Orchestrator: ```bash python your_pipeline.py ``` This will create a Kubernetes pod for each step in your pipeline. You can interact with the pods using `kubectl` commands. For more advanced configuration options and additional details, refer to the [full Kubernetes Orchestrator documentation](../../component-guide/orchestrators/kubernetes.md).
ZenML Scarf
================ File: docs/book/how-to/popular-integrations/mlflow.md ================ --- description: Learn how to use the MLflow Experiment Tracker with ZenML. --- # MLflow Experiment Tracker The ZenML MLflow Experiment Tracker integration and stack component allows you to log and visualize information from your pipeline steps using MLflow, without having to write extra MLflow code. ## Prerequisites To use the MLflow Experiment Tracker, you'll need: - ZenML `mlflow` integration installed (`zenml integration install mlflow -y`) - An MLflow deployment, either local (scenario 1) or remote with proxied artifact storage (scenario 5) ## Configuring the Experiment Tracker There are two main MLflow deployment scenarios: 1. Local (scenario 1): Use a local artifact store, only suitable for running ZenML locally. No extra configuration needed. ```bash zenml experiment-tracker register mlflow_experiment_tracker --flavor=mlflow zenml stack register custom_stack -e mlflow_experiment_tracker ... --set ``` 2. Remote with proxied artifact storage (scenario 5): Can be used with any stack components. Requires authentication configuration. For remote, you'll need to configure authentication using one of: - Basic authentication (not recommended for production) - ZenML secrets (recommended) To use ZenML secrets: ```bash zenml secret create mlflow_secret \ --username= \ --password= zenml experiment-tracker register mlflow \ --flavor=mlflow \ --tracking_username={{mlflow_secret.username}} \ --tracking_password={{mlflow_secret.password}} \ ... ``` ## Using the Experiment Tracker To log information with MLflow in a pipeline step: 1. Enable the experiment tracker using the `@step` decorator 2. Use MLflow's logging or auto-logging capabilities as usual ```python import mlflow @step(experiment_tracker="") def train_step(...): mlflow.tensorflow.autolog() mlflow.log_param(...) mlflow.log_metric(...) mlflow.log_artifact(...) ... ``` ## Viewing Results You can find the URL to the MLflow experiment for a ZenML run: ```python last_run = client.get_pipeline("").last_run trainer_step = last_run.get_step("") tracking_url = trainer_step.run_metadata["experiment_tracker_url"].value ``` This will link to your deployed MLflow instance UI, or the local MLflow experiment file. ## Additional Configuration You can further configure the experiment tracker using `MLFlowExperimentTrackerSettings`: ```python 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 } ) ``` For more details and advanced options, see the [full MLflow Experiment Tracker documentation](../../component-guide/experiment-trackers/mlflow.md).
ZenML Scarf
================ File: docs/book/how-to/popular-integrations/README.md ================ --- icon: puzzle-piece description: Use your favorite tools with ZenML. --- # Popular integrations ZenML is designed to work seamlessly with your favorite tools. This guide will show you how to integrate ZenML with some of the most popular tools in the data science and machine learning ecosystem.
ZenML Scarf
================ File: docs/book/how-to/popular-integrations/skypilot.md ================ --- description: Use Skypilot with ZenML. --- # Skypilot The ZenML SkyPilot VM Orchestrator allows you to provision and manage VMs on any supported cloud provider (AWS, GCP, Azure, Lambda Labs) for running your ML pipelines. It simplifies the process and offers cost savings and high GPU availability. ## Prerequisites To use the SkyPilot VM Orchestrator, you'll need: - ZenML SkyPilot integration for your cloud provider installed (`zenml integration install skypilot_`) - Docker installed and running - A remote artifact store and container registry in your ZenML stack - A remote ZenML deployment - Appropriate permissions to provision VMs on your cloud provider - A service connector configured to authenticate with your cloud provider (not needed for Lambda Labs) ## Configuring the Orchestrator Configuration steps vary by cloud provider: AWS, GCP, Azure: 1. Install the SkyPilot integration and connectors extra for your provider 2. Register a service connector with credentials that have SkyPilot's required permissions 3. Register the orchestrator and connect it to the service connector 4. Register and activate a stack with the new orchestrator ```bash zenml service-connector register -skypilot-vm -t --auto-configure zenml orchestrator register --flavor vm_ zenml orchestrator connect --connector -skypilot-vm zenml stack register -o ... --set ``` Lambda Labs: 1. Install the SkyPilot Lambda integration 2. Register a secret with your Lambda Labs API key 3. Register the orchestrator with the API key secret 4. Register and activate a stack with the new orchestrator ```bash zenml secret create lambda_api_key --scope user --api_key= zenml orchestrator register --flavor vm_lambda --api_key={{lambda_api_key.api_key}} zenml stack register -o ... --set ``` ## Running a Pipeline Once configured, you can run any ZenML pipeline using the SkyPilot VM Orchestrator. Each step will run in a Docker container on a provisioned VM. ## Additional Configuration You can further configure the orchestrator using cloud-specific `Settings` objects: ```python from zenml.integrations.skypilot_.flavors.skypilot_orchestrator__vm_flavor import SkypilotOrchestratorSettings skypilot_settings = SkypilotOrchestratorSettings( cpus="2", memory="16", accelerators="V100:2", use_spot=True, region=, ... ) @pipeline( settings={ "orchestrator": skypilot_settings } ) ``` This allows specifying VM size, spot usage, region, and more. You can also configure resources per step: ```python high_resource_settings = SkypilotOrchestratorSettings(...) @step(settings={"orchestrator": high_resource_settings}) def resource_intensive_step(): ... ``` For more details and advanced options, see the [full SkyPilot VM Orchestrator documentation](../../component-guide/orchestrators/skypilot-vm.md).
ZenML Scarf
================ File: docs/book/how-to/project-setup-and-management/collaborate-with-team/project-templates/create-your-own-template.md ================ --- description: How to create your own ZenML template. --- # Create your own ZenML template Creating your own ZenML template is a great way to standardize and share your ML workflows across different projects or teams. ZenML uses [Copier](https://copier.readthedocs.io/en/stable/) to manage its project templates. Copier is a library that allows you to generate projects from templates. It's simple, versatile, and powerful. Here's a step-by-step guide on how to create your own ZenML template: 1. **Create a new repository for your template.** This will be the place where you store all the code and configuration files for your template. 2. **Define your ML workflows as ZenML steps and pipelines.** You can start by copying the code from one of the existing ZenML templates (like the [starter template](https://github.com/zenml-io/template-starter)) and modifying it to fit your needs. 3. **Create a `copier.yml` file.** This file is used by Copier to define the template's parameters and their default values. You can learn more about this config file [in the copier docs](https://copier.readthedocs.io/en/stable/creating/). 4. **Test your template.** You can use the `copier` command-line tool to generate a new project from your template and check if everything works as expected: ```bash copier copy https://github.com/your-username/your-template.git your-project ``` Replace `https://github.com/your-username/your-template.git` with the URL of your template repository, and `your-project` with the name of the new project you want to create. 5. **Use your template with ZenML.** Once your template is ready, you can use it with the `zenml init` command: ```bash zenml init --template https://github.com/your-username/your-template.git ``` Replace `https://github.com/your-username/your-template.git` with the URL of your template repository. If you want to use a specific version of your template, you can use the `--template-tag` option to specify the git tag of the version you want to use: ```bash zenml init --template https://github.com/your-username/your-template.git --template-tag v1.0.0 ``` Replace `v1.0.0` with the git tag of the version you want to use. That's it! Now you have your own ZenML project template that you can use to quickly set up new ML projects. Remember to keep your template up-to-date with the latest best practices and changes in your ML workflows. Our [Production Guide](../../../../user-guide/production-guide/README.md) documentation is built around the `E2E Batch` project template codes. Most examples will be based on it, so we highly recommend you to install the `e2e_batch` template with `--template-with-defaults` flag before diving deeper into this documentation section, so you can follow this guide along using your own local environment. ```bash mkdir e2e_batch cd e2e_batch zenml init --template e2e_batch --template-with-defaults ```
ZenML Scarf
================ File: docs/book/how-to/project-setup-and-management/collaborate-with-team/project-templates/README.md ================ --- description: Rocketstart your ZenML journey! --- # Project templates What would you need to get a quick understanding of the ZenML framework and start building your ML pipelines? The answer is one of ZenML project templates to cover major use cases of ZenML: a collection of steps and pipelines and, to top it all off, a simple but useful CLI. This is exactly what the ZenML templates are all about! ## List of available project templates
Project Template [Short name]TagsDescription
Starter template [starter]basic scikit-learnAll the basic ML ingredients you need to get you started with ZenML: parameterized steps, a model training pipeline, a flexible configuration and a simple CLI. All created around a representative and versatile model training use-case implemented with the scikit-learn library.
E2E Training with Batch Predictions [e2e_batch]etl hp-tuning model-promotion drift-detection batch-prediction scikit-learnThis project template is a good starting point for anyone starting with ZenML. It consists of two pipelines with the following high-level steps: load, split, and preprocess data; run HP tuning; train and evaluate model performance; promote model to production; detect data drift; run batch inference.
NLP Training Pipeline [nlp]nlp hp-tuning model-promotion training pytorch gradio huggingfaceThis project template is a simple NLP training pipeline that walks through tokenization, training, HP tuning, evaluation and deployment for a BERT or GPT-2 based model and testing locally it with gradio
{% hint style="info" %} Do you have a personal project powered by ZenML that you would like to see here? At ZenML, we are looking for design partnerships and collaboration to help us better understand the real-world scenarios in which MLOps is being used and to build the best possible experience for our users. If you are interested in sharing all or parts of your project with us in the form of a ZenML project template, please [join our Slack](https://zenml.io/slack/) and leave us a message! {% endhint %} ## Using a project template First, to use the templates, you need to have ZenML and its `templates` extras installed: ```bash pip install zenml[templates] ``` {% hint style="warning" %} Note that these templates are not the same thing as the templates used for triggering a pipeline (from the dashboard or via the Python SDK). Those are known as 'Run Templates' and you can read more about them here. {% endhint %} Now, you can generate a project from one of the existing templates by using the `--template` flag with the `zenml init` command: ```bash zenml init --template # example: zenml init --template e2e_batch ``` Running the command above will result in input prompts being shown to you. If you would like to rely on default values for the ZenML project template - you can add `--template-with-defaults` to the same command, like this: ```bash zenml init --template --template-with-defaults # example: zenml init --template e2e_batch --template-with-defaults ```
ZenML Scarf
================ File: docs/book/how-to/project-setup-and-management/collaborate-with-team/access-management.md ================ --- description: A guide on managing user roles and responsibilities in ZenML. --- # Access Management and Roles in ZenML Effective access management is crucial for maintaining security and efficiency in your ZenML projects. This guide will help you understand the different roles within a ZenML server and how to manage access for your team members. ## Typical Roles in an ML Project In an ML project, you will typically have the following roles: - Data Scientists: Primarily work on developing and running pipelines. - MLOps Platform Engineers: Manage the infrastructure and stack components. - Project Owners: Oversee the entire ZenML deployment and manage user access. The above is an estimation of roles that you might have in your team. In your case, the names might be different or there might be more roles, but you can relate the responbilities we discuss in this document to your own project loosely. {% hint style="info" %} You can create [Roles in ZenML Pro](../../../getting-started/zenml-pro/roles.md) with a given set of permissions and assign them to either Users or Teams that represent your real-world team structure. Sign up for a free trial to try it yourself: https://cloud.zenml.io/ {% endhint %} ## Service Connectors: Gateways to External Services Service connectors are how different cloud services are integrated with ZenML. They are used to abstract away the credentials and other configurations needed to access these services. Ideally, you would want that only the MLOps Platform Engineers have access for creating and managing connectors. This is because they are closest to your infrastructure and can make informed decisions about what authentication mechanisms to use and more. Other team members can use connectors to create stack components that talk to the external services but should not have to worry about setting them and shouldn't have access to the credentials used to configure them. Let's look at an example of how this works in practice. Imagine you have a `DataScientist` role in your ZenML server. This role should only be able to use the connectors to create stack components and run pipelines. They shouldn't have access to the credentials used to configure these connectors. Therefore, the permissions for this role could look like the following: ![Data Scientist Permissions](../../../.gitbook/assets/data_scientist_connector_role.png) You can notice that the role doesn't grant the data scientist permissions to create, update, or delete connectors, or read their secret values. On the other hand, the `MLOpsPlatformEngineer` role has the permissions to create, update, and delete connectors, as well as read their secret values. The permissions for this role could look like the following: ![MLOps Platform Engineer Permissions](../../../.gitbook/assets/platform_engineer_connector_role.png) {% hint style="info" %} Note that you can only use the RBAC features in ZenML Pro. Learn more about roles in ZenML Pro [here](../../../getting-started/zenml-pro/roles.md). {% endhint %} Learn more about the best practices in managing credentials and recommended roles in our [Managing Stacks and Components guide](../../infrastructure-deployment/stack-deployment/README.md). ## Who is responsible for upgrading the ZenML server? The decision to upgrade your ZenML server is usually taken by your Project Owners after consulting with all the teams using the server. This is because there might be teams with conflicting requirements and moving to a new version of ZenML (that might come with upgrades to certain libraries) can break code for some users. {% hint style="info" %} You can choose to have different servers for different teams and that can alleviate some of the pressure to upgrade if you have multiple teams using the same server. ZenML Pro offers [multi-tenancy](../../../getting-started/zenml-pro/tenants.md) out of the box, for situations like these. Sign up for a free trial to try it yourself: https://cloud.zenml.io/ {% endhint %} Performing the upgrade itself is a task that typically falls on the MLOps Platform Engineers. They should: - ensure that all data is backed up before performing the upgrade - no service disruption or downtime happens during the upgrade and more. Read in detail about the best practices for upgrading your ZenML server in the [Best Practices for Upgrading ZenML Servers](../../../how-to/manage-zenml-server/best-practices-upgrading-zenml.md) guide. ## Who is responsible for migrating and maintaining pipelines? When you upgrade to a new version of ZenML, you might have to test if your code works as expected and if the syntax is up to date with what ZenML expects. Although we do our best to make new releases compatible with older versions, there might be some breaking changes that you might have to address. The pipeline code itself is typically owned by the Data Scientist, but the Platform Engineer is responsible for making sure that new changes can be tested in a safe environment without impacting existing workflows. This involves setting up a new server and doing a staged upgrade and other strategies. The Data Scientist should also check out the release notes, and the migration guide where applicable when upgrading the code. Read more about the best practices for upgrading your ZenML server and your code in the [Best Practices for Upgrading ZenML Servers](../../../how-to/manage-zenml-server/best-practices-upgrading-zenml.md) guide. ## Best Practices for Access Management Apart from the role-specific tasks we discussed so far, there are some general best practices you should follow to ensure a secure and well-managed ZenML environment that supports collaboration while maintaining proper access controls. - Regular Audits: Conduct periodic reviews of user access and permissions. - Role-Based Access Control (RBAC): Implement RBAC to streamline permission management. - Least Privilege: Grant minimal necessary permissions to each role. - Documentation: Maintain clear documentation of roles, responsibilities, and access policies. {% hint style="info" %} The Role-Based Access Control (RBAC) and assigning of permissions is only available for ZenML Pro users. {% endhint %} By following these guidelines, you can ensure a secure and well-managed ZenML environment that supports collaboration while maintaining proper access controls.
ZenML Scarf
================ File: docs/book/how-to/project-setup-and-management/collaborate-with-team/README.md ================ --- icon: people-group --- ================ File: docs/book/how-to/project-setup-and-management/collaborate-with-team/shared-components-for-teams.md ================ --- description: Sharing code and libraries within teams. --- # Shared Libraries and Logic for Teams Teams often need to collaborate on projects, share versioned logic, and implement cross-cutting functionality that benefits the entire organization. Sharing code libraries allows for incremental improvements, increased robustness, and standardization across projects. This guide will cover two main aspects of sharing code within teams using ZenML: 1. What can be shared 2. How to distribute shared components ## What Can Be Shared ZenML offers several types of custom components that can be shared between teams: ### Custom Flavors Custom flavors are special integrations that don't come built-in with ZenML. These can be implemented and shared as follows: 1. Create the custom flavor in a shared repository. 2. Implement the custom stack component as described in the [ZenML documentation](../../infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md#implementing-a-custom-stack-component-flavor). 3. Register the component using the ZenML CLI, for example in the case of a custom artifact store flavor: ```bash zenml artifact-store flavor register ``` ### Custom Steps Custom steps can be created and shared via a separate repository. Team members can reference these components as they would normally reference Python modules. ### Custom Materializers Custom materializers are common components that teams often need to share. To implement and share a custom materializer: 1. Create the materializer in a shared repository. 2. Implement the custom materializer as described in the [ZenML documentation](https://docs.zenml.io/how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types). 3. Team members can import and use the shared materializer in their projects. ## How to Distribute Shared Components There are several methods to distribute and use shared components within a team: ### Shared Private Wheels Using shared private wheels is an effective approach to sharing code within a team. This method packages Python code for internal distribution without making it publicly available. #### Benefits of Using Shared Private Wheels - Packaged format: Easy to install using pip - Version management: Simplifies managing different code versions - Dependency management: Automatically installs specified dependencies - Privacy: Can be hosted on internal PyPI servers - Smooth integration: Imported like any other Python package #### Setting Up Shared Private Wheels 1. Create a private PyPI server or use a service like [AWS CodeArtifact](https://aws.amazon.com/codeartifact/). 2. [Build your code](https://packaging.python.org/en/latest/tutorials/packaging-projects/) [into wheel format](https://opensource.com/article/23/1/packaging-python-modules-wheels). 3. Upload the wheel to your private PyPI server. 4. Configure pip to use the private PyPI server in addition to the public one. 5. Install the private packages using pip, just like public packages. ### Using Shared Libraries with `DockerSettings` When running pipelines with remote orchestrators, ZenML generates a `Dockerfile` at runtime. You can use the `DockerSettings` class to specify how to include your shared libraries in this Docker image. #### Installing Shared Libraries Here are some ways to include shared libraries using `DockerSettings`. Either specify a list of requirements: ```python import os from zenml.config import DockerSettings from zenml import pipeline docker_settings = DockerSettings( requirements=["my-simple-package==0.1.0"], environment={'PIP_EXTRA_INDEX_URL': f"https://{os.environ.get('PYPI_TOKEN', '')}@my-private-pypi-server.com/{os.environ.get('PYPI_USERNAME', '')}/"} ) @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` Or you can also use a requirements file: ```python docker_settings = DockerSettings(requirements="/path/to/requirements.txt") @pipeline(settings={"docker": docker_settings}) def my_pipeline(...): ... ``` The `requirements.txt` file would specify the private index URL in the following way, for example: ``` --extra-index-url https://YOURTOKEN@my-private-pypi-server.com/YOURUSERNAME/ my-simple-package==0.1.0 ``` For information on using private PyPI repositories to share your code, see our [documentation on how to use a private PyPI repository](../../../how-to/customize-docker-builds/how-to-use-a-private-pypi-repository.md). ## Best Practices Regardless of what you're sharing or how you're distributing it, consider these best practices: - Use version control for shared code repositories. Version control systems like Git allow teams to collaborate on code effectively. They provide a central repository where all team members can access the latest version of the shared components and libraries. - Implement proper access controls for private PyPI servers or shared repositories. To ensure the security of proprietary code and libraries, it's crucial to set up appropriate access controls. This may involve using authentication mechanisms, managing user permissions, and regularly auditing access logs. - Maintain clear documentation for shared components and libraries. Comprehensive and up-to-date documentation is essential for the smooth usage and maintenance of shared code. It should cover installation instructions, API references, usage examples, and any specific guidelines or best practices. - Regularly update shared libraries and communicate changes to the team. As the project evolves, it's important to keep shared libraries updated with the latest bug fixes, performance improvements, and feature enhancements. Establish a process for regularly updating and communicating these changes to the team. - Consider setting up continuous integration for shared libraries to ensure quality and compatibility. Continuous integration (CI) helps maintain the stability and reliability of shared components. By automatically running tests and checks on each code change, CI can catch potential issues early and ensure compatibility across different environments and dependencies. By leveraging these methods for sharing code and libraries, teams can collaborate more effectively, maintain consistency across projects, and accelerate development processes within the ZenML framework.
ZenML Scarf
================ File: docs/book/how-to/project-setup-and-management/collaborate-with-team/stacks-pipelines-models.md ================ --- description: A guide on how to organize stacks, pipelines, models, and artifacts in ZenML. --- # Organizing Stacks, Pipelines, Models, and Artifacts In ZenML, pipelines, stacks and models form a crucial part of your project's architecture and how you choose to use them dictates how well organized your code and workflow is. This section will give you an overview of how to think about these concepts and how to best utilize them. Before we begin, here is a quick overview of the concepts we will be discussing: - **Stacks**: [Stacks](../../../user-guide/production-guide/understand-stacks.md) represent the configuration of tools and infrastructure that your pipelines can run on. A stack is built of multiple stack components like an orchestrator, a container registry, an artifact store, etc. Each of these components deal with one part of your workflow and work together to run your pipeline. - **Pipelines**: [Pipelines](../../../user-guide/starter-guide/create-an-ml-pipeline.md) are a series of steps that each represent a specific task in your ML workflow and are executed in a sequence that ZenML determines from your pipeline definition. Pipelines help you automate many tasks, standardize your executions, and add visibility into what your code is doing. - **Models**: [Models](../../model-management-metrics/model-control-plane/README.md) are entities that groups pipelines, artifacts, metadata, and other crucial business data together. You may think of a ZenML Model as a "project" or a "workspace" that spans multiple pipelines. - **Artifacts**: [Artifacts](../../../user-guide/starter-guide/manage-artifacts.md) are the output of a pipeline step that you want to track and reuse across multiple pipelines. Understanding the relationships between stacks, pipelines, models, and artifacts is crucial for effective MLOps with ZenML. ## How many Stacks do I need? A stack provides the infrastructure and tools for running pipelines. Think of a stack as a representation of your execution environment in which your pipelines are run. This comprises both the hardware like the orchestration environment and any MLOps tools you use in your workflow. This way, Stacks allow you to seamlessly transition between different environments (e.g., local, staging, production) while keeping your pipeline code consistent. You can learn more about organizing and managing stacks in the [Managing Stacks and Components](../../infrastructure-deployment/stack-deployment/README.md) guide. You don't need a separate stack for each pipeline; instead, you can run multiple pipelines on the same stack. A stack is meant to be created once and then reused across multiple users and pipelines. This helps in the following ways: - reduces the overhead of configuring your infrastructure every time you run a pipeline. - provides a consistent environment for your pipelines to run in, promoting reproducibility. - reduces risk of errors when it comes to what hardware and tool configurations to use. ## How do I organize my Pipelines, Models, and Artifacts? Pipelines, Models, and Artifacts form the core of your ML workflow in ZenML. All of your project logic is organized around these concepts and as such, it helps to understand how they interact with each other and how to structure your code to make the most out of them. ### Pipelines A pipeline typically encompasses the entire ML workflow, including data preparation, model training, and evaluation. It's a good practice to have a separate pipeline for different tasks like training and inference. This makes your pipelines more modular and easier to manage. Here's some of the benefits: - Separation of pipelines by the nature of the task allows you to [run them independently as needed](../../../how-to/pipeline-development/develop-locally/local-prod-pipeline-variants.md). For example, you might train a model in a training pipeline only once a week but run inference on new data every day. - It becomes easier to manage and update your code as your project grows more complex. - Different people can work on the code for the pipelines without interfering with each other. - It helps you organize your runs better. ### Models Models are what tie related pipelines together. A Model in ZenML is a collection of data artifacts, model artifacts, pipelines and metadata that can all be tied to a specific project. As such, it is good practice to use a Model to move data between pipelines. Continuing with the example of a training and an inference pipeline, you can use a ZenML Model to handover the trained model from the training pipeline to the inference pipeline. The Model Control Plane allows you to set Stages for specific model versions that can help with this. ### Artifacts Artifacts are the output of a pipeline step that you want to track and reuse across multiple pipelines. They can be anything from a dataset to a trained model. It is a good practice to name your artifacts appropriately to make them easy to identify and reuse. Every pipeline run that results in a unique execution of a pipeline step produces a new version of your artifact. This ensures that there's a clear history and traceability of your data and model artifacts. Artifacts can be tied to a Model for better organization and visibility across pipelines. You can choose to log metadata about your artifacts which will then show up in the Model Control Plane. ## So how do I put this all together? ![Diagram showing how Models bring together Pipelines and Artifacts](../../../.gitbook/assets/model_pipeline_artifact.png) Let's go through a real-world example to see how we can use Stacks, Pipelines, Models, and Artifacts together. Imagine there are two people in your team working on a classification model, Bob and Alice. Here's how the workflow would look like with ZenML: - They create three pipelines: one for feature engineering, one for training the model, and one for producing predictions. - They set up a [repository for their project](../../project-setup-and-management/setting-up-a-project-repository/README.md) and start building their pipelines collaboratively. Let's assume Bob builds the feature engineering and training pipeline and Alice builds the inference pipeline. - To test their pipelines locally, they both have a `default` stack with a local orchestrator and a local artifact store. This allows them to quickly iterate on their code without deploying any infrastructure or incurring any costs. - While building the inference pipeline, Alice needs to make sure that the preprocessing step in her pipeline is the same as the one used while training. It might even involve the use of libraries that are not publicily available and she follows the [Shared Libraries and Logic for Teams](./shared-components-for-teams.md) guide to help with this. - Bob's training pipeline produces a model artifact, which Alice's inference pipeline requires as input. It also produces other artifacts such as metrics and a model checkpoint that are logged as artifacts in the pipeline run. - To allow easy access to model and data artifacts, they [use a ZenML Model](../../model-management-metrics/model-control-plane/associate-a-pipeline-with-a-model.md) which ties the pipelines, models and artifacts together. Now Alice can just [reference the right model name and find the model artifact she needs.](../../model-management-metrics/model-control-plane/load-artifacts-from-model.md) - It is also critical that the right model version from the training pipeline is used in the inference pipeline. The [Model Control Plane](../../model-management-metrics/model-control-plane/README.md) helps Bob to keep track of the different versions and to easily compare them. Bob can then [promote the best performing model version to the `production` stage](../../model-management-metrics/model-control-plane/promote-a-model.md) which Alice's pipeline can then consume. - Alice's inference pipeline produces a new artifact, in this case a new dataset containing the predictions of the model. Results can also be added as metadata to the model version, allowing easy comparisons. This is a very simple example, but it shows how you can use ZenML to structure your ML workflow. You can use the same principles for more complex workflows. ## Rules of Thumb Here are some general guidelines to help you organize your ZenML projects effectively: ### Models - Create one Model per distinct machine learning use-case or business problem - Use Models to group related pipelines, artifacts, and metadata together - Leverage the Model Control Plane to manage model versions and stages (e.g., staging, production) ### Stacks - Maintain separate stacks for different environments (development, staging, production) - Share production and staging stacks across teams to ensure consistency - Keep local development stacks simple for quick iterations ### Naming and Organization - Use consistent naming conventions for pipelines, artifacts, and models - Leverage tags to organize and filter resources (e.g., `environment:production`, `team:fraud-detection`) - Document stack configurations and pipeline dependencies - Keep pipeline code modular and reusable across different environments Following these guidelines will help maintain a clean and scalable MLOps workflow as your project grows.
ZenML Scarf
================ File: docs/book/how-to/project-setup-and-management/setting-up-a-project-repository/connect-your-git-repository.md ================ --- description: >- Tracking your code and avoiding unnecessary Docker builds by connecting your git repo. --- # Connect your git repository A code repository in ZenML refers to a remote storage location for your code. Some commonly known code repository platforms include [GitHub](https://github.com/) and [GitLab](https://gitlab.com/).

A visual representation of how the code repository fits into the general ZenML architecture.

Code repositories enable ZenML to keep track of the code version that you use for your pipeline runs. Additionally, running a pipeline that is tracked in a registered code repository can [speed up the Docker image building for containerized stack components](../../../how-to/customize-docker-builds/how-to-reuse-builds.md) by eliminating the need to rebuild Docker images each time you change one of your source code files. Learn more about how code repositories benefit development [here](../../../how-to/customize-docker-builds/how-to-reuse-builds.md). ## Registering a code repository If you are planning to use one of the [available implementations of code repositories](connect-your-git-repository.md#available-implementations), first, you need to install the corresponding ZenML integration: ``` zenml integration install ``` Afterward, code repositories can be registered using the CLI: ```shell zenml code-repository register --type= [--CODE_REPOSITORY_OPTIONS] ``` For concrete options, check out the section on the [`GitHubCodeRepository`](connect-your-git-repository.md#github), the [`GitLabCodeRepository`](connect-your-git-repository.md#gitlab) or how to develop and register a [custom code repository implementation](connect-your-git-repository.md#developing-a-custom-code-repository). ## Available implementations ZenML comes with builtin implementations of the code repository abstraction for the `GitHub` and `GitLab` platforms, but it's also possible to use a [custom code repository implementation](connect-your-git-repository.md#developing-a-custom-code-repository). ### GitHub ZenML provides built-in support for using GitHub as a code repository for your ZenML pipelines. You can register a GitHub code repository by providing the URL of the GitHub instance, the owner of the repository, the name of the repository, and a GitHub Personal Access Token (PAT) with access to the repository. Before registering the code repository, first, you have to install the corresponding integration: ```sh zenml integration install github ``` Afterward, you can register a GitHub code repository by running the following CLI command: ```shell zenml code-repository register --type=github \ --url= --owner= --repository= \ --token= ``` where \ is the name of the code repository you are registering, \ is the owner of the repository, \ is the name of the repository, \ is your GitHub Personal Access Token and \ is the URL of the GitHub instance which defaults to `https://github.com.` You will need to set a URL if you are using GitHub Enterprise. {% hint style="warning" %} Please refer to the section on using secrets for stack configuration in order to securely store your GitHub Personal Access Token. ```shell # Using central secrets management zenml secret create github_secret \ --pa_token= # Then reference the username and password zenml code-repository register ... --token={{github_secret.pa_token}} ... ``` {% endhint %} After registering the GitHub code repository, ZenML will automatically detect if your source files are being tracked by GitHub and store the commit hash for each pipeline run.
How to get a token for GitHub 1. Go to your GitHub account settings and click on [Developer settings](https://github.com/settings/tokens?type=beta). 2. Select "Personal access tokens" and click on "Generate new token". 3. Give your token a name and a description. ![](../../../.gitbook/assets/github-fine-grained-token-name.png) 4. We recommend selecting the specific repository and then giving `contents` read-only access. ![](../../../.gitbook/assets/github-token-set-permissions.png) ![](../../../.gitbook/assets/github-token-permissions-overview.png) 5. Click on "Generate token" and copy the token to a safe place. ![](../../../.gitbook/assets/copy-github-fine-grained-token.png)
### GitLab ZenML also provides built-in support for using GitLab as a code repository for your ZenML pipelines. You can register a GitLab code repository by providing the URL of the GitLab project, the group of the project, the name of the project, and a GitLab Personal Access Token (PAT) with access to the project. Before registering the code repository, first, you have to install the corresponding integration: ```sh zenml integration install gitlab ``` Afterward, you can register a GitLab code repository by running the following CLI command: ```shell zenml code-repository register --type=gitlab \ --url= --group= --project= \ --token= ``` where `` is the name of the code repository you are registering, `` is the group of the project, `` is the name of the project, \ is your GitLab Personal Access Token, and \ is the URL of the GitLab instance which defaults to `https://gitlab.com.` You will need to set a URL if you have a self-hosted GitLab instance. {% hint style="warning" %} Please refer to the section on using secrets for stack configuration in order to securely store your GitLab Personal Access Token. ```shell # Using central secrets management zenml secret create gitlab_secret \ --pa_token= # Then reference the username and password zenml code-repository register ... --token={{gitlab_secret.pa_token}} ... ``` {% endhint %} After registering the GitLab code repository, ZenML will automatically detect if your source files are being tracked by GitLab and store the commit hash for each pipeline run.
How to get a token for GitLab 1. Go to your GitLab account settings and click on [Access Tokens](https://gitlab.com/-/profile/personal\_access\_tokens). 2. Name the token and select the scopes that you need (e.g. `read_repository`, `read_user`, `read_api`) ![](../../../.gitbook/assets/gitlab-generate-access-token.png) 3. Click on "Create personal access token" and copy the token to a safe place. ![](../../../.gitbook/assets/gitlab-copy-access-token.png)
## Developing a custom code repository If you're using some other platform to store your code, and you still want to use a code repository in ZenML, you can implement and register a custom code repository. First, you'll need to subclass and implement the abstract methods of the `zenml.code_repositories.BaseCodeRepository` class: ```python class BaseCodeRepository(ABC): """Base class for code repositories.""" @abstractmethod def login(self) -> None: """Logs into the code repository.""" @abstractmethod def download_files( self, commit: str, directory: str, repo_sub_directory: Optional[str] ) -> None: """Downloads files from the code repository to a local directory. Args: commit: The commit hash to download files from. directory: The directory to download files to. repo_sub_directory: The subdirectory in the repository to download files from. """ @abstractmethod def get_local_context( self, path: str ) -> Optional["LocalRepositoryContext"]: """Gets a local repository context from a path. Args: path: The path to the local repository. Returns: The local repository context object. """ ``` After you're finished implementing this, you can register it as follows: ```shell # The `CODE_REPOSITORY_OPTIONS` are key-value pairs that your implementation will receive # as configuration in its __init__ method. This will usually include stuff like the username # and other credentials necessary to authenticate with the code repository platform. zenml code-repository register --type=custom --source=my_module.MyRepositoryClass \ [--CODE_REPOSITORY_OPTIONS] ```
ZenML Scarf
================ File: docs/book/how-to/project-setup-and-management/setting-up-a-project-repository/README.md ================ --- icon: paw description: Setting your team up for success with a well-architected ZenML project. --- # Setting up a Well-Architected ZenML Project Welcome to the guide on setting up a well-architected ZenML project. This section will provide you with a comprehensive overview of best practices, strategies, and considerations for structuring your ZenML projects to ensure scalability, maintainability, and collaboration within your team. ## The Importance of a Well-Architected Project A well-architected ZenML project is crucial for the success of your machine learning operations (MLOps). It provides a solid foundation for your team to develop, deploy, and maintain ML models efficiently. By following best practices and leveraging ZenML's features, you can create a robust and flexible MLOps pipeline that scales with your needs. ## Key Components of a Well-Architected ZenML Project ### Repository Structure A clean and organized repository structure is essential for any ZenML project. This includes: - Proper folder organization for pipelines, steps, and configurations - Clear separation of concerns between different components - Consistent naming conventions Learn more about setting up your repository in the [Set up repository guide](./set-up-repository.md). ### Version Control and Collaboration Integrating your ZenML project with version control systems like Git is crucial for team collaboration and code management. This allows for: - Makes creating pipeline builds faster, as you can leverage the same image and [have ZenML download code from your repository](../../infrastructure-deployment/customize-docker-builds/how-to-reuse-builds.md#use-code-repositories-to-speed-up-docker-build-times). - Easy tracking of changes - Collaboration among team members Discover how to connect your Git repository in the [Set up a repository guide](./set-up-repository.md). ### Stacks, Pipelines, Models, and Artifacts Understanding the relationship between stacks, models, and pipelines is key to designing an efficient ZenML project: - Stacks: Define your infrastructure and tool configurations - Models: Represent your machine learning models and their metadata - Pipelines: Encapsulate your ML workflows - Artifacts: Track your data and model outputs Learn about organizing these components in the [Organizing Stacks, Pipelines, Models, and Artifacts guide](../collaborate-with-team/stacks-pipelines-models.md). ### Access Management and Roles Proper access management ensures that team members have the right permissions and responsibilities: - Define roles such as data scientists, MLOps engineers, and infrastructure managers - Set up [service connectors](../../infrastructure-deployment/auth-management/README.md) and manage authorizations - Establish processes for pipeline maintenance and server upgrades - Leverage [Teams in ZenML Pro](../../../getting-started/zenml-pro/teams.md) to assign roles and permissions to a group of users, to mimic your real-world team roles. Explore access management strategies in the [Access Management and Roles guide](../collaborate-with-team/access-management.md). ### Shared Components and Libraries Leverage shared components and libraries to promote code reuse and standardization across your team: - Custom flavors, steps, and materializers - Shared private wheels for internal distribution - Handling authentication for specific libraries Find out more about sharing code in the [Shared Libraries and Logic for Teams guide](../collaborate-with-team/shared-components-for-teams.md). ### Project Templates Utilize project templates to kickstart your ZenML projects and ensure consistency: - Use pre-made templates for common use cases - Create custom templates tailored to your team's needs Learn about using and creating project templates in the [Project Templates guide](../collaborate-with-team/project-templates/README.md). ### Migration and Maintenance As your project evolves, you may need to migrate existing codebases or upgrade your ZenML server: - Strategies for migrating legacy code to newer ZenML versions - Best practices for upgrading ZenML servers Discover migration strategies and maintenance best practices in the [Migration and Maintenance guide](../../advanced-topics/manage-zenml-server/best-practices-upgrading-zenml.md#upgrading-your-code). ## Getting Started To begin building your well-architected ZenML project, start by exploring the guides in this section. Each guide provides in-depth information on specific aspects of project setup and management. Remember, a well-architected project is an ongoing process. Regularly review and refine your project structure, processes, and practices to ensure they continue to meet your team's evolving needs. By following these guidelines and leveraging ZenML's powerful features, you'll be well on your way to creating a robust, scalable, and collaborative MLOps environment.
ZenML Scarf
================ File: docs/book/how-to/project-setup-and-management/setting-up-a-project-repository/set-up-repository.md ================ --- description: Recommended repository structure and best practices. --- # Set up your repository While it doesn't matter how you structure your ZenML project, here is a recommended project structure the core team often uses: ```markdown . ├── .dockerignore ├── Dockerfile ├── steps │ ├── loader_step │ │ ├── .dockerignore (optional) │ │ ├── Dockerfile (optional) │ │ ├── loader_step.py │ │ └── requirements.txt (optional) │ └── training_step │ └── ... ├── pipelines │ ├── training_pipeline │ │ ├── .dockerignore (optional) │ │ ├── config.yaml (optional) │ │ ├── Dockerfile (optional) │ │ ├── training_pipeline.py │ │ └── requirements.txt (optional) │ └── deployment_pipeline │ └── ... ├── notebooks │ └── *.ipynb ├── requirements.txt ├── .zen └── run.py ``` All ZenML [Project templates](using-project-templates.md#generating-project-from-a-project-template) are modeled around this basic structure. The `steps` and `pipelines` folders contain the steps and pipelines defined in your project. If your project is simpler you can also just keep your steps at the top level of the `steps` folder without the need so structure them in subfolders. {% hint style="info" %} It might also make sense to register your repository as a code repository. These enable ZenML to keep track of the code version that you use for your pipeline runs. Additionally, running a pipeline that is tracked in [a registered code repository](./connect-your-git-repository.md) can speed up the Docker image building for containerized stack components by eliminating the need to rebuild Docker images each time you change one of your source code files. Learn more about these in [connecting your Git repository](https://docs.zenml.io/how-to/setting-up-a-project-repository/connect-your-git-repository). {% endhint %} #### Steps Keep your steps in separate Python files. This allows you to optionally keep their utils, dependencies, and Dockerfiles separate. #### Logging ZenML records the root python logging handler's output into the artifact store as a side-effect of running a step. Therefore, when writing steps, use the `logging` module to record logs, to ensure that these logs then show up in the ZenML dashboard. ```python # Use ZenML handler from zenml.logger import get_logger logger = get_logger(__name__) ... @step def training_data_loader(): # This will show up in the dashboard logger.info("My logs") ``` #### Pipelines Just like steps, keep your pipelines in separate Python files. This allows you to optionally keep their utils, dependencies, and Dockerfiles separate. It is recommended that you separate the pipeline execution from the pipeline definition so that importing the pipeline does not immediately run it. {% hint style="warning" %} Do not give pipelines or pipeline instances the name "pipeline". Doing this will overwrite the imported `pipeline` and decorator and lead to failures at later stages if more pipelines are decorated there. {% endhint %} {% hint style="info" %} Pipeline names are their unique identifiers, so using the same name for different pipelines will create a mixed history where two runs of a pipeline are two very different entities. {% endhint %} #### .dockerignore Containerized orchestrators and step operators load your complete project files into a Docker image for execution. To speed up the process and reduce Docker image sizes, exclude all unnecessary files (like data, virtual environments, git repos, etc.) within the `.dockerignore`. #### Dockerfile (optional) By default, ZenML uses the official [zenml Docker image](https://hub.docker.com/r/zenmldocker/zenml) as a base for all pipeline and step builds. You can use your own `Dockerfile` to overwrite this behavior. Learn more [here](../../../how-to/customize-docker-builds/README.md). #### Notebooks Collect all your notebooks in one place. #### .zen By running `zenml init` at the root of your project, you define the project scope for ZenML. In ZenML terms, this will be called your "source's root". This will be used to resolve import paths and store configurations. Although this is optional, it is recommended that you do this for all of your projects. This is especially important if you are using Jupyter noteeboks in your project as these require you to have initialized a `.zen` file. {% hint style="warning" %} All of your import paths should be relative to the source's root. {% endhint %} #### run.py Putting your pipeline runners in the root of the repository ensures that all imports that are defined relative to the project root resolve for the pipeline runner. In case there is no `.zen` defined this also defines the implicit source's root.
ZenML Scarf
================ File: docs/book/how-to/project-setup-and-management/interact-with-secrets.md ================ --- icon: user-secret description: Registering and using secrets. --- # Interact with secrets ## What is a ZenML secret? ZenML secrets are groupings of **key-value pairs** which are securely stored in the ZenML secrets store. Additionally, a secret always has a **name** that allows you to fetch or reference them in your pipelines and stacks. ## How to create a secret {% tabs %} {% tab title="CLI" %} To create a secret with a name `` and a key-value pair, you can run the following CLI command: ```shell zenml secret create \ --= \ --= # Another option is to use the '--values' option and provide key-value pairs in either JSON or YAML format. zenml secret create \ --values='{"key1":"value2","key2":"value2"}' ``` Alternatively, you can create the secret in an interactive session (in which ZenML will query you for the secret keys and values) by passing the `--interactive/-i` parameter: ```shell zenml secret create -i ``` For secret values that are too big to pass as a command line argument, or have special characters, you can also use the special `@` syntax to indicate to ZenML that the value needs to be read from a file: ```bash zenml secret create \ --key=@path/to/file.txt \ ... # Alternatively, you can utilize the '--values' option by specifying a file path containing key-value pairs in either JSON or YAML format. zenml secret create \ --values=@path/to/file.txt ``` The CLI also includes commands that can be used to list, update and delete secrets. A full guide on using the CLI to create, access, update and delete secrets is available [here](https://sdkdocs.zenml.io/latest/cli/#zenml.cli--secrets-management). **Interactively register missing secrets for your stack** If you're using components with [secret references](interact-with-secrets.md#reference-secrets-in-stack-component-attributes-and-settings) in your stack, you need to make sure that all the referenced secrets exist. To make this process easier, you can use the following CLI command to interactively register all secrets for a stack: ```shell zenml stack register-secrets [] ``` {% endtab %} {% tab title="Python SDK" %} The ZenML client API offers a programmatic interface to create, e.g.: ```python from zenml.client import Client client = Client() client.create_secret( name="my_secret", values={ "username": "admin", "password": "abc123" } ) ``` Other Client methods used for secrets management include `get_secret` to fetch a secret by name or id, `update_secret` to update an existing secret, `list_secrets` to query the secrets store using a variety of filtering and sorting criteria, and `delete_secret` to delete a secret. The full Client API reference is available [here](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-client/). {% endtab %} {% endtabs %} ## Set scope for secrets ZenML secrets can be scoped to a user. This allows you to create secrets that are only accessible to one user. By default, all created secrets are scoped to the active user. To create a secret and scope it to your active user instead, you can pass the `--scope` argument to the CLI command: ```shell zenml secret create \ --scope user \ --= \ --= ``` Scopes also act as individual namespaces. When you are referencing a secret by name in your pipelines and stacks, ZenML will look for a secret with that name scoped to the active user. ## Accessing registered secrets ### Reference secrets in stack component attributes and settings Some of the components in your stack require you to configure them with sensitive information like passwords or tokens, so they can connect to the underlying infrastructure. Secret references allow you to configure these components in a secure way by not specifying the value directly but instead referencing a secret by providing the secret name and key. Referencing a secret for the value of any string attribute of your stack components, simply specify the attribute using the following syntax: `{{.}}` For example: {% tabs %} {% tab title="CLI" %} ```shell # Register a secret called `mlflow_secret` with key-value pairs for the # username and password to authenticate with the MLflow tracking server # Using central secrets management zenml secret create mlflow_secret \ --username=admin \ --password=abc123 # Then 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}} \ ... ``` {% endtab %} {% endtabs %} When using secret references in your stack, ZenML will validate that all secrets and keys referenced in your stack components exist before running a pipeline. This helps us fail early so your pipeline doesn't fail after running for some time due to some missing secret. This validation by default needs to fetch and read every secret to make sure that both the secret and the specified key-value pair exist. This can take quite some time and might fail if you don't have permission to read secrets. You can use the environment variable `ZENML_SECRET_VALIDATION_LEVEL` to disable or control the degree to which ZenML validates your secrets: * Setting it to `NONE` disables any validation. * Setting it to `SECRET_EXISTS` only validates the existence of secrets. This might be useful if the machine you're running on only has permission to list secrets but not actually read their values. * Setting it to `SECRET_AND_KEY_EXISTS` (the default) validates both the secret existence as well as the existence of the exact key-value pair. ### Fetch secret values in a step If you are using [centralized secrets management](interact-with-secrets.md), you can access secrets directly from within your steps through the ZenML `Client` API. This allows you to use your secrets for querying APIs from within your step without hard-coding your access keys: ```python from zenml import step from zenml.client import Client @step def secret_loader() -> None: """Load the example secret from the server.""" # Fetch the secret from ZenML. secret = Client().get_secret( < SECRET_NAME >) # `secret.secret_values` will contain a dictionary with all key-value # pairs within your secret. authenticate_to_some_api( username=secret.secret_values["username"], password=secret.secret_values["password"], ) ... ```
ZenML Scarf
================ File: docs/book/how-to/project-setup-and-management/README.md ================ --- icon: building-columns --- # Project Setup and Management This section covers all aspects of setting up and managing ZenML projects. ================ File: docs/book/how-to/trigger-pipelines/README.md ================ --- icon: bell-concierge description: There are numerous ways to trigger a pipeline --- # Trigger a pipeline (Run Templates) In ZenML, the simplest way to execute a run is to use your pipeline function: ```python from zenml import step, pipeline @step # Just add this decorator def load_data() -> dict: training_data = [[1, 2], [3, 4], [5, 6]] labels = [0, 1, 0] return {'features': training_data, 'labels': labels} @step def train_model(data: dict) -> None: total_features = sum(map(sum, data['features'])) total_labels = sum(data['labels']) # Train some model here... print( f"Trained model using {len(data['features'])} data points. " f"Feature sum is {total_features}, label sum is {total_labels}." ) @pipeline # This function combines steps together def simple_ml_pipeline(): dataset = load_data() train_model(dataset) if __name__ == "__main__": simple_ml_pipeline() ``` However, there are other ways to trigger a pipeline, specifically a pipeline with a remote stack (remote orchestrator, artifact store, and container registry). ## Run Templates **Run Templates** are pre-defined, parameterized configurations for your ZenML pipelines that can be easily executed from the ZenML dashboard or via our Client/REST API. Think of them as blueprints for your pipeline runs, ready to be customized on the fly. {% hint style="success" %} This is a [ZenML Pro](https://zenml.io/pro)-only feature. Please [sign up here](https://cloud.zenml.io) to get access. {% endhint %} ![Working with Templates](../../../.gitbook/assets/run-templates.gif)
Use templates: Python SDKuse-templates-python.md
Use templates: CLIuse-templates-cli.md
Use templates: Dashboarduse-templates-dashboard.md
Use templates: Rest APIuse-templates-rest-api.md
ZenML Scarf
================ File: docs/book/how-to/trigger-pipelines/use-templates-cli.md ================ --- description: Create a template using the ZenML CLI --- {% hint style="success" %} This is a [ZenML Pro](https://zenml.io/pro)-only feature. Please [sign up here](https://cloud.zenml.io) to get access. {% endhint %} ## Create a template You can use the ZenML CLI to create a run template: ```bash # The will be `run.my_pipeline` if you defined a # pipeline with name `my_pipeline` in a file called `run.py` zenml pipeline create-run-template --name= ``` {% hint style="warning" %} You need to have an active **remote stack** while running this command or you can specify one with the `--stack` option. {% endhint %}
ZenML Scarf
================ File: docs/book/how-to/trigger-pipelines/use-templates-dashboard.md ================ --- description: Create and run a template over the ZenML Dashboard --- {% hint style="success" %} This is a [ZenML Pro](https://zenml.io/pro)-only feature. Please [sign up here](https://cloud.zenml.io) to get access. {% endhint %} ## Create a template In order to create a template over the dashboard, go a pipeline run that you executed on a remote stack (i.e. at least a remote orchestrator, artifact store, and container registry): ![Create Templates on the dashboard](../../../.gitbook/assets/run-templates-create-1.png) Click on `+ New Template`, give it a name and click `Create`: ![Template Details](../../../.gitbook/assets/run-templates-create-2.png) ## Run a template using the dashboard In order to run a template from the dashboard: - You can either click `Run a Pipeline` on the main `Pipelines` page, or - You can go to a specific template page and click on `Run Template`. Either way, you will be forwarded to a page where you will see the `Run Details`. Here, you have the option to upload a `.yaml` [configurations file](../pipeline-development/use-configuration-files/README.md) or change the configuration on the go by using our editor. ![Run Details](../../../.gitbook/assets/run-templates-run-1.png) Once you run the template, a new run will be executed on the same stack as the original run was executed on.
ZenML Scarf
================ File: docs/book/how-to/trigger-pipelines/use-templates-python.md ================ --- description: Create and run a template using the ZenML Python SDK --- {% hint style="success" %} This is a [ZenML Pro](https://zenml.io/pro)-only feature. Please [sign up here](https://cloud.zenml.io) to get access. {% endhint %} ## Create a template You can use the ZenML client to create a run template: ```python from zenml.client import Client run = Client().get_pipeline_run() Client().create_run_template( name=, deployment_id=run.deployment_id ) ``` {% hint style="warning" %} You need to select **a pipeline run that was executed on a remote stack** (i.e. at least a remote orchestrator, artifact store, and container registry) {% endhint %} You can also create a template directly from your pipeline definition by running the following code while having a **remote stack** active: ```python from zenml import pipeline @pipeline def my_pipeline(): ... template = my_pipeline.create_run_template(name=) ``` ## Run a template You can use the ZenML client to run a template: ```python from zenml.client import Client template = Client().get_run_template() config = template.config_template # [OPTIONAL] ---- modify the config here ---- Client().trigger_pipeline( template_id=template.id, run_configuration=config, ) ``` Once you trigger the template, a new run will be executed on the same stack as the original run was executed on. ## Advanced Usage: Run a template from another pipeline It is also possible to use the same logic to run a pipeline within another pipeline: ```python import pandas as pd from zenml import pipeline, step from zenml.artifacts.unmaterialized_artifact import UnmaterializedArtifact from zenml.artifacts.utils import load_artifact from zenml.client import Client from zenml.config.pipeline_run_configuration import PipelineRunConfiguration @step def trainer(data_artifact_id: str): df = load_artifact(data_artifact_id) @pipeline def training_pipeline(): trainer() @step def load_data() -> pd.Dataframe: ... @step def trigger_pipeline(df: UnmaterializedArtifact): # By using UnmaterializedArtifact we can get the ID of the artifact run_config = PipelineRunConfiguration( steps={"trainer": {"parameters": {"data_artifact_id": df.id}}} ) Client().trigger_pipeline("training_pipeline", run_configuration=run_config) @pipeline def loads_data_and_triggers_training(): df = load_data() trigger_pipeline(df) # Will trigger the other pipeline ``` Read more about the [PipelineRunConfiguration](https://sdkdocs.zenml.io/latest/core_code_docs/core-config/#zenml.config.pipeline_run_configuration.PipelineRunConfiguration) and [`trigger_pipeline`](https://sdkdocs.zenml.io/latest/core_code_docs/core-client/#zenml.client.Client) function object in the [SDK Docs](https://sdkdocs.zenml.io/). Read more about Unmaterialized Artifacts [here](../data-artifact-management/complex-usecases/unmaterialized-artifacts.md).
ZenML Scarf
================ File: docs/book/how-to/trigger-pipelines/use-templates-rest-api.md ================ --- description: Create and run a template over the ZenML Rest API --- {% hint style="success" %} This is a [ZenML Pro](https://zenml.io/pro)-only feature. Please [sign up here](https://cloud.zenml.io) to get access. {% endhint %} ## Run a template Triggering a pipeline from the REST API **only** works if you've created at least one run template for that pipeline. As a pre-requisite, you need a pipeline name. After you have it, there are three calls that need to be made in order to trigger a pipeline from the REST API: 1. `GET /pipelines?name=` -> This returns a response, where a can be copied 2. `GET /run_templates?pipeline_id=` -> This returns a list of responses where a can be chosen 3. `POST /run_templates//runs` -> This runs the pipeline. You can pass the [PipelineRunConfiguration](https://sdkdocs.zenml.io/latest/core_code_docs/core-config/#zenml.config.pipeline_run_configuration.PipelineRunConfiguration) in the body ## A working example {% hint style="info" %} Learn how to get a bearer token for the curl commands [here](../../../reference/api-reference.md#using-a-bearer-token-to-access-the-api-programmatically). {% endhint %} Here is an example. Let's say would we like to re-run a pipeline called `training`. We first query the `/pipelines` endpoint: ```shell curl -X 'GET' \ '/api/v1/pipelines?hydrate=false&name=training' \ -H 'accept: application/json' \ -H 'Authorization: Bearer ' ```

Identifying the pipeline ID

We can take the ID from any object in the list of responses. In this case, the is `c953985e-650a-4cbf-a03a-e49463f58473` in the response. After this, we take the pipeline ID and call the`/run_templates?pipeline_id=` API: ```shell curl -X 'GET' \ '/api/v1/run_templates?hydrate=false&logical_operator=and&page=1&size=20&pipeline_id=b826b714-a9b3-461c-9a6e-1bde3df3241d' \ -H 'accept: application/json' \ -H 'Authorization: Bearer ' ``` We can now take the from this response. Here it is `b826b714-a9b3-461c-9a6e-1bde3df3241d`.

Identifying the template ID

Finally, we can use the template ID to trigger the pipeline with a different configuration: ```shell curl -X 'POST' \ '/api/v1/run_templates/b826b714-a9b3-461c-9a6e-1bde3df3241d/runs' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -d '{ "steps": {"model_trainer": {"parameters": {"model_type": "rf"}}} }' ``` A positive response means your pipeline has been re-triggered with a different config!
ZenML Scarf
================ File: docs/book/how-to/debug-and-solve-issues.md ================ --- icon: bug description: A guide to debug common issues and get help. --- # Debug and solve issues If you stumbled upon this page, chances are you're facing issues with using ZenML. This page documents suggestions and best practices to let you debug, get help, and solve issues quickly. ### When to get help? We suggest going through the following checklist before asking for help: * Search on Slack using the built-in Slack search function at the top of the page. ![Searching on Slack.](../.gitbook/assets/slack_search_bar.png) * Search on [GitHub issues](https://github.com/zenml-io/zenml/issues). * Search the [docs](https://docs.zenml.io) using the search bar in the top right corner of the page. ![Searching on docs page.](../.gitbook/assets/doc_search_bar.png) * Check out the [common errors](debug-and-solve-issues.md#most-common-errors) section below. * Understand the problem by studying the [additional logs](debug-and-solve-issues.md#41-additional-logs) and [client/server logs](debug-and-solve-issues.md#client-and-server-logs). Chances are you'd find your answers there. If you can't find any clue, then it's time to post your question on [Slack](https://zenml.io/slack). ### How to post on Slack? When posting on Slack it's useful to provide the following information (when applicable) so that we get a complete picture before jumping into solutions. #### 1. System Information Let us know relevant information about your system. We recommend running the following in your terminal and attaching the output to your question. ```shell zenml info -a -s ``` You can optionally include information about specific packages where you're having problems by using the `-p` option. For example, if you're having problems with the `tensorflow` package, you can run: ```shell zenml info -p tensorflow ``` The output should look something like this: ```yaml ZENML_LOCAL_VERSION: 0.40.2 ZENML_SERVER_VERSION: 0.40.2 ZENML_SERVER_DATABASE: mysql ZENML_SERVER_DEPLOYMENT_TYPE: alpha ZENML_CONFIG_DIR: /Users/my_username/Library/Application Support/zenml ZENML_LOCAL_STORE_DIR: /Users/my_username/Library/Application Support/zenml/local_stores ZENML_SERVER_URL: https://someserver.zenml.io ZENML_ACTIVE_REPOSITORY_ROOT: /Users/my_username/coding/zenml/repos/zenml PYTHON_VERSION: 3.9.13 ENVIRONMENT: native SYSTEM_INFO: {'os': 'mac', 'mac_version': '13.2'} ACTIVE_STACK: default ACTIVE_USER: some_user TELEMETRY_STATUS: disabled ANALYTICS_CLIENT_ID: xxxxxxx-xxxxxxx-xxxxxxx ANALYTICS_USER_ID: xxxxxxx-xxxxxxx-xxxxxxx ANALYTICS_SERVER_ID: xxxxxxx-xxxxxxx-xxxxxxx INTEGRATIONS: ['airflow', 'aws', 'azure', 'dash', 'evidently', 'facets', 'feast', 'gcp', 'github', 'graphviz', 'huggingface', 'kaniko', 'kubeflow', 'kubernetes', 'lightgbm', 'mlflow', 'neptune', 'neural_prophet', 'pillow', 'plotly', 'pytorch', 'pytorch_lightning', 's3', 'scipy', 'sklearn', 'slack', 'spark', 'tensorboard', 'tensorflow', 'vault', 'wandb', 'whylogs', 'xgboost'] ``` System information provides more context to your issue and also eliminates the need for anyone to ask when they're trying to help. This increases the chances of your question getting answered and saves everyone's time. #### 2. What happened? Tell us briefly: * What were you trying to achieve? * What did you expect to happen? * What actually happened? #### 3. How to reproduce the error? Walk us through how to reproduce the same error you had step-by-step, whenever possible. Use the format you prefer. Write it in text or record a video, whichever lets you get the issue at hand across to us! #### 4. Relevant log output As a general rule of thumb, always attach relevant log outputs and the full error traceback to help us understand what happened under the hood. If the full error traceback does not fit into a text message, attach a file or use a service like [Pastebin](https://pastebin.com/) or [Github's Gist](https://gist.github.com/). Along with the error traceback, we recommend to always share the output of the following commands: * `zenml status` * `zenml stack describe` When applicable, also attach logs of the orchestrator. For example, if you're using the Kubeflow orchestrator, include the logs of the pod that was running the step that failed. Usually, the default log you see in your terminal is sufficient, in the event it's not, then it's useful to provide additional logs. Additional logs are not shown by default, you'll have to toggle an environment variable for it. Read the next section to find out how. **4.1 Additional logs** When the default logs are not helpful, ambiguous, or do not point you to the root of the issue, you can toggle the value of the `ZENML_LOGGING_VERBOSITY` environment variable to change the type of logs shown. The default value of `ZENML_LOGGING_VERBOSITY` environment variable is: ``` ZENML_LOGGING_VERBOSITY=INFO ``` You can pick other values such as `WARN`, `ERROR`, `CRITICAL`, `DEBUG` to change what's shown in the logs. And export the environment variable in your terminal. For example in Linux: ```shell export ZENML_LOGGING_VERBOSITY=DEBUG ``` Read more about how to set environment variables for: * For [Linux](https://linuxize.com/post/how-to-set-and-list-environment-variables-in-linux/). * For [macOS](https://youngstone89.medium.com/setting-up-environment-variables-in-mac-os-28e5941c771c). * For [Windows](https://www.computerhope.com/issues/ch000549.htm). ### Client and server logs When facing a ZenML Server-related issue, you can view the logs of the server to introspect deeper. To achieve this, run: ```shell zenml logs ``` The logs from a healthy server should look something like this: ```shell INFO:asyncio:Syncing pipeline runs... 2022-10-19 09:09:18,195 - zenml.zen_stores.metadata_store - DEBUG - Fetched 4 steps for pipeline run '13'. (metadata_store.py:315) 2022-10-19 09:09:18,359 - zenml.zen_stores.metadata_store - DEBUG - Fetched 0 inputs and 4 outputs for step 'importer'. (metadata_store.py:427) 2022-10-19 09:09:18,461 - zenml.zen_stores.metadata_store - DEBUG - Fetched 0 inputs and 4 outputs for step 'importer'. (metadata_store.py:427) 2022-10-19 09:09:18,516 - zenml.zen_stores.metadata_store - DEBUG - Fetched 2 inputs and 2 outputs for step 'normalizer'. (metadata_store.py:427) 2022-10-19 09:09:18,606 - zenml.zen_stores.metadata_store - DEBUG - Fetched 0 inputs and 4 outputs for step 'importer'. (metadata_store.py:427) ``` ### Most common errors This section documents frequently encountered errors among users and solutions to each. #### Error initializing rest store Typically, the error presents itself as: ```bash RuntimeError: Error initializing rest store with URL 'http://127.0.0.1:8237': HTTPConnectionPool(host='127.0.0.1', port=8237): Max retries exceeded with url: /api/v1/login (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 61] Connection refused')) ``` If you restarted your machine after starting the local ZenML server with `zenml login --local`, then you have to run `zenml login --local` again after each restart. Local ZenML deployments don't survive machine restarts. #### Column 'step\_configuration' cannot be null ```bash sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1048, "Column 'step_configuration' cannot be null") ``` This happens when a step configuration is too long. We changed the limit from 4K to 65K chars, but it could still happen if you have excessively long strings in your config. #### 'NoneType' object has no attribute 'name' This is also a common error you might encounter when you do not have the necessary stack components registered on the stack. For example: ```shell ╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮ │ /home/dnth/Documents/zenml-projects/nba-pipeline/run_pipeline.py:24 in │ │ │ │ 21 │ reference_data_splitter, │ │ 22 │ TrainingSplitConfig, │ │ 23 ) │ │ ❱ 24 from steps.trainer import random_forest_trainer │ │ 25 from steps.encoder import encode_columns_and_clean │ │ 26 from steps.importer import ( │ │ 27 │ import_season_schedule, │ │ │ │ /home/dnth/Documents/zenml-projects/nba-pipeline/steps/trainer.py:24 in │ │ │ │ 21 │ max_depth: int = 10000 │ │ 22 │ target_col: str = "FG3M" │ │ 23 │ │ ❱ 24 @step(enable_cache=False, experiment_tracker=experiment_tracker.name) │ │ 25 def random_forest_trainer( │ │ 26 │ train_df_x: pd.DataFrame, │ │ 27 │ train_df_y: pd.DataFrame, │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯ AttributeError: 'NoneType' object has no attribute 'name' ``` In the above error snippet, the `step` on line 24 expects an experiment tracker but could not find it on the stack. To solve it, register an experiment tracker of your choice on the stack. For instance: ```shell zenml experiment-tracker register mlflow_tracker --flavor=mlflow ``` and update your stack with the experiment tracker: ```shell zenml stack update -e mlflow_tracker ``` This also applies to all other [stack components](../component-guide/README.md).
ZenML Scarf
================ File: docs/book/reference/api-reference.md ================ --- icon: ruler description: See the ZenML API reference. --- # API reference The ZenML server is a FastAPI application, therefore the OpenAPI-compliant docs are available at `/docs` or `/redoc` of your ZenML server: {% hint style="info" %} In the local case (i.e. using `zenml login --local`, the docs are available on `http://127.0.0.1:8237/docs`) {% endhint %} ![ZenML API docs](../.gitbook/assets/zenml_api_docs.png) ![ZenML API Redoc](../.gitbook/assets/zenml_api_redoc.png) ## Using a bearer token to access the API programmatically If you are using the ZenML server API using the above pages, it is enough to be logged in to your ZenML account in the same browser session. However, in order to do this programmatically, the following steps need to be followed: 1. Create a [service account](../how-to/manage-zenml-server/connecting-to-zenml/connect-with-a-service-account.md): ```shell zenml service-account create myserviceaccount ``` This will print out the ``, you can use in the next command. 2. Get an access token by using the `/api/v1/login` endpoint: ```shell curl -X 'POST' \ '/api/v1/login' \ -H 'accept: application/json' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -d 'grant_type=zenml-api-key&username=&password='\''&client_id=&device_code=' ``` This will return a response like this: ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI3MGJjZTg5NC1hN2VjLTRkOTYtYjE1Ny1kOTZkYWY5ZWM2M2IiLCJpc3MiOiJmMGQ5NjI1Ni04YmQyLTQxZDctOWVjZi0xMmYwM2JmYTVlMTYiLCJhdWQiOiJmMGQ5NjI1Ni04YmQyLTQxZDctOWVjZi0xMmYwM2JmYTVlMTYiLCJleHAiOjE3MTk0MDk0NjAsImFwaV9rZXlfaWQiOiIzNDkyM2U0NS0zMGFlLTRkMjctODZiZS0wZGRhNTdkMjA5MDcifQ.ByB1ngCPtBenGE6UugsWC6Blga3qPqkAiPJUSFDR-u4", "token_type": "bearer", "expires_in": 3600, "refresh_token": null, "scope": null } ``` 3. Use the access token to make subsequent curl commands: ```shell curl -X 'GET' \ '/api/v1/pipelines?hydrate=false&name=training' \ -H 'accept: application/json' \ -H 'Authorization: Bearer ' ```
ZenML Scarf
================ File: docs/book/reference/community-and-content.md ================ --- icon: heart description: All possible ways for our community to get in touch with ZenML. --- # Community & content The ZenML team and community have put together a list of references that can be used to get in touch with the development team of ZenML and develop a deeper understanding of the framework. ### Slack Channel: Get help from the community The ZenML [Slack channel](https://zenml.io/slack) is the main gathering point for the community. Not only is it the best place to get in touch with the core team of ZenML, but it is also a great way to discuss new ideas and share your ZenML projects with the community. If you have a question, there is a high chance someone else might have already answered it on Slack! ### Social Media: Bite-sized updates We are active on [LinkedIn](https://www.linkedin.com/company/zenml) and [Twitter](https://twitter.com/zenml\_io) where we post bite-sized updates on releases, events, and MLOps in general. Follow us to interact and stay up to date! We would appreciate it if you could comment on and share our posts so more people can benefit from our work at ZenML! ### YouTube Channel: Video tutorials, workshops, and more Our [YouTube channel](https://www.youtube.com/c/ZenML) features a growing set of videos that take you through the entire framework. Go here if you are a visual learner, and follow along with some tutorials. ### Public roadmap The feedback from our community plays a significant role in the development of ZenML. That's why we have a [public roadmap](https://zenml.io/roadmap) that serves as a bridge between our users and our development team. If you have ideas regarding any new features or want to prioritize one over the other, feel free to share your thoughts here or vote on existing ideas. ### Blog On our [Blog](https://zenml.io/blog/) page, you can find various articles written by our team. We use it as a platform to share our thoughts and explain the implementation process of our tool, its new features, and the thought process behind them. ### Podcast We also have a [Podcast](https://podcast.zenml.io/) series that brings you interviews and discussions with industry leaders, top technology professionals, and others. We discuss the latest developments in machine learning, deep learning, and artificial intelligence, with a particular focus on MLOps, or how trained models are used in production. ### Newsletter You can also subscribe to our [Newsletter](https://zenml.io/newsletter-signup) where we share what we learn as we develop open-source tooling for production machine learning. You will also get all the exciting news about ZenML in general.
ZenML Scarf
================ File: docs/book/reference/environment-variables.md ================ --- icon: earth-africa description: How to control ZenML behavior with environmental variables. --- # Environment Variables There are a few pre-defined environmental variables that can be used to control the behavior of ZenML. See the list below with default values and options: ## Logging verbosity ```bash export ZENML_LOGGING_VERBOSITY=INFO ``` Choose from `INFO`, `WARN`, `ERROR`, `CRITICAL`, `DEBUG`. ## Disable step logs Usually, ZenML [stores step logs in the artifact store](../how-to/control-logging/enable-or-disable-logs-storing.md), but this can sometimes cause performance bottlenecks, especially if the code utilizes progress bars. If you want to configure whether logged output from steps is stored or not, set the `ZENML_DISABLE_STEP_LOGS_STORAGE` environment variable to `true`. Note that this will mean that logs from your steps will no longer be stored and thus won't be visible on the dashboard anymore. ```bash export ZENML_DISABLE_STEP_LOGS_STORAGE=false ``` ## ZenML repository path To configure where ZenML will install and look for its repository, set the environment variable `ZENML_REPOSITORY_PATH`. ```bash export ZENML_REPOSITORY_PATH=/path/to/somewhere ``` ## Analytics Please see [our full page](global-settings.md#usage-analytics) on what analytics are tracked and how you can opt out, but the quick summary is that you can set this to `false` if you want to opt out of analytics. ```bash export ZENML_ANALYTICS_OPT_IN=false ``` ## Debug mode Setting to `true` switches to developer mode: ```bash export ZENML_DEBUG=true ``` ## Active stack Setting the `ZENML_ACTIVE_STACK_ID` to a specific UUID will make the corresponding stack the active stack: ```bash export ZENML_ACTIVE_STACK_ID= ``` ## Prevent pipeline execution When `true`, this prevents a pipeline from executing: ```bash export ZENML_PREVENT_PIPELINE_EXECUTION=false ``` ## Disable rich traceback Set to `false` to disable the [`rich` traceback](https://rich.readthedocs.io/en/stable/traceback.html): ```bash export ZENML_ENABLE_RICH_TRACEBACK=true ``` ## Disable colorful logging If you wish to disable colorful logging, set the following environment variable: ```bash ZENML_LOGGING_COLORS_DISABLED=true ``` Note that setting this on the [client environment](../how-to/pipeline-development/configure-python-environments/README.md#client-environment-or-the-runner-environment) (e.g. your local machine which runs the pipeline) will automatically disable colorful logging on remote orchestrators. If you wish to disable it locally, but turn on for remote orchestrators, you can set the `ZENML_LOGGING_COLORS_DISABLED` environment variable in your orchestrator's environment as follows: ```python docker_settings = DockerSettings(environment={"ZENML_LOGGING_COLORS_DISABLED": "false"}) # Either add it to the decorator @pipeline(settings={"docker": docker_settings}) def my_pipeline() -> None: my_step() # Or configure the pipelines options my_pipeline = my_pipeline.with_options( settings={"docker": docker_settings} ) ``` ## ZenML global config path To set the path to the global config file, used by ZenML to manage and store the state for a number of settings, set the environment variable as follows: ```bash export ZENML_CONFIG_PATH=/path/to/somewhere ``` ## Server configuration For more information on server configuration, see the [ZenML Server documentation](../getting-started/deploying-zenml/deploy-with-docker.md#zenml-server-configuration-options) for more, especially the section entitled "ZenML server configuration options". ## Client configuration Setting the `ZENML_STORE_URL` and `ZENML_STORE_API_KEY` environment variables automatically connects your ZenML Client to the specified server. This method is particularly useful when you are using the ZenML client in an automated CI/CD workload environment like GitHub Actions or GitLab CI or in a containerized environment like Docker or Kubernetes: ```bash export ZENML_STORE_URL=https://... export ZENML_STORE_API_KEY= ```
ZenML Scarf
================ File: docs/book/reference/faq.md ================ --- description: Find answers to the most frequently asked questions about ZenML. icon: circle-question --- # FAQ #### Why did you build ZenML? We built it because we scratched our own itch while deploying multiple machine-learning models in production over the past three years. Our team struggled to find a simple yet production-ready solution whilst developing large-scale ML pipelines. We built a solution for it that we are now proud to share with all of you! Read more about this backstory [on our blog here](https://blog.zenml.io/why-zenml/). #### Is ZenML just another orchestrator like Airflow, Kubeflow, Flyte, etc? Not really! An orchestrator in MLOps is the system component that is responsible for executing and managing the execution of an ML pipeline. ZenML is a framework that allows you to run your pipelines on whatever orchestrator you like, and we coordinate with all the other parts of an ML system in production. There are [standard orchestrators](../component-guide/orchestrators/orchestrators.md) that ZenML supports out-of-the-box, but you are encouraged to [write your own orchestrator](../component-guide/orchestrators/custom.md) in order to gain more control as to exactly how your pipelines are executed! #### Can I use the tool `X`? How does the tool `Y` integrate with ZenML? Take a look at our [documentation](https://docs.zenml.io) (in particular the [component guide](../component-guide/README.md)), which contains instructions and sample code to support each integration that ZenML supports out-of-the-box. You can also check out [our integration test code](https://github.com/zenml-io/zenml/tree/main/tests/integration/examples) to see active examples of many of our integrations in action. The ZenML team and community are constantly working to include more tools and integrations to the above list (check out the [roadmap](https://zenml.io/roadmap) for more details). You can [upvote features](https://zenml.io/discussion) you'd like and add your ideas to the roadmap. Most importantly, ZenML is extensible, and we encourage you to use it with whatever other tools you require as part of your ML process and system(s). Check out [our documentation on how to get started](../introduction.md) with extending ZenML to learn more! #### Do you support Windows? ZenML officially supports Windows if you're using WSL. Much of ZenML will also work on Windows outside a WSL environment, but we don't officially support it and some features don't work (notably anything that requires spinning up a server process). #### Do you support Macs running on Apple Silicon? Yes, ZenML does support Macs running on Apple Silicon. You just need to make sure that you set the following environment variable: ```bash export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES ``` This is a known issue with how forking works on Macs running on Apple Silicon and it will enable you to use ZenML and the server. This environment variable is needed if you are working with a local server on your Mac, but if you're just using ZenML as a client / CLI and connecting to a deployed server then you don't need to set it. #### How can I make ZenML work with my custom tool? How can I extend or build on ZenML? This depends on the tool and its respective MLOps category. We have a full guide on this over [here](../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md)! #### How can I contribute? We develop ZenML together with our community! To get involved, the best way to get started is to select any issue from the [`good-first-issue` label](https://github.com/zenml-io/zenml/labels/good%20first%20issue). If you would like to contribute, please review our [Contributing Guide](https://github.com/zenml-io/zenml/blob/main/CONTRIBUTING.md) for all relevant details. #### How can I speak with the community? The first point of the call should be [our Slack group](https://zenml.io/slack/). Ask your questions about bugs or specific use cases and someone from the core team will respond. #### Which license does ZenML use? ZenML is distributed under the terms of the Apache License Version 2.0. A complete version of the license is available in the [LICENSE.md](https://github.com/zenml-io/zenml/blob/main/LICENSE) in this repository. Any contribution made to this project will be licensed under the Apache License Version 2.0.
ZenML Scarf
================ File: docs/book/reference/global-settings.md ================ --- icon: gear description: Understanding the global settings of your ZenML installation. --- # Global settings The information about the global settings of ZenML on a machine is kept in a folder commonly referred to as the **ZenML Global Config Directory** or the **ZenML Config Path**. The location of this folder depends on the operating system type and the current system user, but is usually located in the following locations: * Linux: `~/.config/zenml` * Mac: `~/Library/Application Support/zenml` * Windows: `C:\Users\%USERNAME%\AppData\Local\zenml` The default location may be overridden by setting the `ZENML_CONFIG_PATH` environment variable to a custom value. The current location of the global config directory used on a system can be retrieved by running the following commands: ```shell # The output will tell you something like this: # Using configuration from: '/home/stefan/.config/zenml' zenml status python -c 'from zenml.utils.io_utils import get_global_config_directory; print(get_global_config_directory())' ``` {% hint style="warning" %} Manually altering or deleting the files and folders stored under the ZenML global config directory is not recommended, as this can break the internal consistency of the ZenML configuration. As an alternative, ZenML provides CLI commands that can be used to manage the information stored there: * `zenml analytics` - manage the analytics settings * `zenml clean` - to be used only in case of emergency, to bring the ZenML configuration back to its default factory state * `zenml downgrade` - downgrade the ZenML version in the global configuration to match the version of the ZenML package installed in the current environment. Read more about this in the [ZenML Version Mismatch](global-settings.md#version-mismatch-downgrading) section. {% endhint %} The first time that ZenML is run on a machine, it creates the global config directory and initializes the default configuration in it, along with a default Stack: ``` Initializing the ZenML global configuration version to 0.13.2 Creating default user 'default' ... Creating default stack for user 'default'... The active stack is not set. Setting the active stack to the default stack. Using the default store for the global config. Unable to find ZenML repository in your current working directory (/tmp/folder) or any parent directories. If you want to use an existing repository which is in a different location, set the environment variable 'ZENML_REPOSITORY_PATH'. If you want to create a new repository, run zenml init. Running without an active repository root. Using the default local database. ┏━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓ ┃ ACTIVE │ STACK NAME │ SHARED │ OWNER │ ARTIFACT_STORE │ ORCHESTRATOR ┃ ┠────────┼────────────┼────────┼─────────┼────────────────┼──────────────┨ ┃ 👉 │ default │ ❌ │ default │ default │ default ┃ ┗━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛ ``` The following is an example of the layout of the global config directory immediately after initialization: ``` /home/stefan/.config/zenml <- Global Config Directory ├── config.yaml <- Global Configuration Settings └── local_stores <- Every Stack component that stores information | locally will have its own subdirectory here. ├── a1a0d3d0-d552-4a80-be09-67e5e29be8ee <- e.g. Local Store path for the | `default` local Artifact Store └── default_zen_store | └── zenml.db <- SQLite database where ZenML data (stacks, components, etc) are stored by default. ``` As shown above, the global config directory stores the following information: 1. The `config.yaml` file stores the global configuration settings: the unique ZenML client ID, the active database configuration, the analytics-related options, and the active Stack. This is an example of the `config.yaml` file contents immediately after initialization: ```yaml active_stack_id: ... analytics_opt_in: true store: database: ... url: ... username: ... ... user_id: d980f13e-05d1-4765-92d2-1dc7eb7addb7 version: 0.13.2 ``` 2. The `local_stores` directory is where some "local" flavors of stack components, such as the local artifact store, or a local MLFlow experiment tracker, persist data locally. Every local stack component will have its own subdirectory here named after the stack component's unique UUID. One notable example is the local artifact store flavor that, when part of the active stack, stores all the artifacts generated by pipeline runs in the designated local directory. 3. The `zenml.db` in the `default_zen_store` directory is the default SQLite database where ZenML stores all information about the stacks, stack components, custom stack component flavors, etc. In addition to the above, you may also find the following files and folders under the global config directory, depending on what you do with ZenML: * `kubeflow` - this is where the Kubeflow orchestrators that are part of a stack store some of their configuration and logs. ## Usage analytics In order to help us better understand how the community uses ZenML, the pip package reports **anonymized** usage statistics. You can always opt out by using the CLI command: ```bash zenml analytics opt-out ``` #### Why does ZenML collect analytics? In addition to the community at large, **ZenML** is created and maintained by a startup based in Munich, Germany called [ZenML GmbH](https://zenml.io). We're a team of techies that love MLOps and want to build tools that fellow developers would love to use in their daily work. [This is us](https://zenml.io/company#CompanyTeam) if you want to put faces to the names! However, in order to improve **ZenML** and understand how it is being used, we need to use analytics to have an overview of how it is used 'in the wild'. This not only helps us find bugs but also helps us prioritize features and commands that might be useful in future releases. If we did not have this information, all we really get is pip download statistics and chatting with people directly, which while being valuable, is not enough to seriously better the tool as a whole. #### How does ZenML collect these statistics? We use [Segment](https://segment.com) as the data aggregation library for all our analytics. However, before any events get sent to [Segment](https://segment.com), they first go through a central ZenML analytics server. This added layer allows us to put various countermeasures to incidents such as getting spammed with events and enables us to have a more optimized tracking process. The client code is entirely visible and can be seen in the [`analytics`](https://github.com/zenml-io/zenml/tree/main/src/zenml/analytics) module of our main repository. #### If I share my email, will you spam me? No, we won't. Our sole purpose of contacting you will be to ask for feedback (e.g. in the shape of a user interview). These interviews help the core team understand usage better and prioritize feature requests. If you have any concerns about data privacy and the usage of personal information, please [contact us](mailto:support@zenml.io), and we will try to alleviate any concerns as soon as possible. ## Version mismatch (downgrading) If you've recently downgraded your ZenML version to an earlier release or installed a newer version on a different environment on the same machine, you might encounter an error message when running ZenML that says: ```shell `The ZenML global configuration version (%s) is higher than the version of ZenML currently being used (%s).` ``` We generally recommend using the latest ZenML version. However, there might be cases where you need to match the global configuration version with the version of ZenML installed in the current environment. To do this, run the following command: ```shell zenml downgrade ``` {% hint style="warning" %} Note that downgrading the ZenML version may cause unexpected behavior, such as model schema validation failures or even data loss. In such cases, you may need to purge the local database and re-initialize the global configuration to bring it back to its default factory state. To do this, run the following command: ```shell zenml clean ``` {% endhint %}
ZenML Scarf
================ File: docs/book/reference/how-do-i.md ================ --- icon: face-thinking description: Links to common use cases, workflows and tasks using ZenML. --- # How do I...? **Last Updated**: December 13, 2023 Some common questions that we get asked are: * **contribute** to ZenML's open-source codebase? Please read [our Contribution guide](https://github.com/zenml-io/zenml/blob/main/CONTRIBUTING.md) for more information. For small features and bug fixes, please open a pull request as described in the guide. For anything bigger, it is worth [posting a message in Slack](https://zenml.io/slack/) or [creating an issue](https://github.com/zenml-io/zenml/issues/new/choose) so we can best discuss and support your plans. * **custom components**: adding them to ZenML? Please start by [reading the general documentation page](../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md) on implementing a custom stack component which offers some general advice on what you'll need to do. From there, each of the custom stack component types has a dedicated section about adding your own custom components. For example, for adding custom orchestrators you would [visit this page](../component-guide/orchestrators/custom.md). * **dependency clashes** mitigation with ZenML? Check out [our dedicated documentation page](../how-to/pipeline-development/configure-python-environments/handling-dependencies.md) on some ways you can try to solve these dependency and versioning issues. * **deploy cloud infrastructure** and/or MLOps stacks? ZenML is designed to be stack-agnostic, so you can use it with any cloud infrastructure or MLOps stack. Each of the documentation pages for stack components explain how to deploy these components on the most popular cloud providers. * **deploy ZenML** on my internal company cluster? Read [the documentation on self-hosted ZenML deployments](../getting-started/deploying-zenml/README.md) in which several options are presented. * **hyperparameter tuning**? [Our dedicated documentation guide](../how-to/pipeline-development/build-pipelines/hyper-parameter-tuning.md) on implementing this is the place to learn more. * **reset** things when something goes wrong? To reset your ZenML client, you can run `zenml clean` which will wipe your local metadata database and reset your client. Note that this is a destructive action, so feel free to [reach out to us on Slack](https://zenml.io/slack/) before doing this if you are unsure. * **steps that create other steps AKA dynamic pipelines and steps**? Please read our [general information on how to compose steps + pipelines together](../user-guide/starter-guide/create-an-ml-pipeline.md) to start with. You might also find the code examples in [our guide to implementing hyperparameter tuning](../how-to/pipeline-development/build-pipelines/hyper-parameter-tuning.md) which is related to this topic. * **templates**: using starter code with ZenML? [Project templates](../how-to/project-setup-and-management/collaborate-with-team/project-templates/README.md) allow you to get going quickly with ZenML. We recommend the Starter template (`starter`) for most use cases which gives you a basic scaffold and structure around which you can write your own code. You can also build templates for others inside a Git repository and use them with ZenML's templates functionality. * **upgrade** my ZenML client and/or server? Upgrading your ZenML client package is as simple as running `pip install --upgrade zenml` in your terminal. For upgrading your ZenML server, please refer to [the dedicated documentation section](../how-to/manage-zenml-server/upgrade-zenml-server.md) which covers most of the ways you might do this as well as common troubleshooting steps. * use a \ stack component? For information on how to use a specific stack component, please refer to [the component guide](../component-guide/README.md) which contains all our tips and advice on how to use each integration and component with ZenML.
ZenML Scarf
================ File: docs/book/reference/python-client.md ================ --- icon: python description: Interacting with your ZenML instance through the ZenML Client. --- # Python Client Pipelines, runs, stacks, and many other ZenML resources are stored and versioned in a database within your ZenML instance behind the scenes. The ZenML Python `Client` allows you to fetch, update, or even create any of these resources programmatically in Python. {% hint style="info" %} In all other programming languages and environments, you can interact with ZenML resources through the REST API endpoints of your ZenML server instead. Checkout the `/docs/` page of your server for an overview of all available endpoints. {% endhint %} ### Usage Example The following example shows how to use the ZenML Client to fetch the last 10 pipeline runs that you ran yourself on the stack that you have currently set: ```python from zenml.client import Client client = Client() my_runs_on_current_stack = client.list_pipeline_runs( stack_id=client.active_stack_model.id, # on current stack user_id=client.active_user.id, # ran by you sort_by="desc:start_time", # last 10 size=10, ) for pipeline_run in my_runs_on_current_stack: print(pipeline_run.name) ``` ### List of Resources These are the main ZenML resources that you can interact with via the ZenML Client: #### Pipelines, Runs, Artifacts * **Pipelines**: The pipelines that were implicitly tracked when running ZenML pipelines. * **Pipeline Runs**: Information about all pipeline runs that were executed on your ZenML instance. * **Run Templates**: Templates to run pipelines from the server or dashboard. * **Step Runs**: The steps of all pipeline runs. Mainly useful for directly fetching a specific step of a run by its ID. * **Artifacts**: Information about all artifacts that were written to your artifact stores as part of pipeline runs. * **Schedules**: Metadata about the schedules that you have used to [schedule pipeline runs](../how-to/pipeline-development/build-pipelines/schedule-a-pipeline.md). * **Builds**: The pipeline-specific Docker images that were created when [containerizing your pipeline](../how-to/customize-docker-builds/README.md). * **Code Repositories**: The git code repositories that you have connected with your ZenML instance. See [here](../user-guide/production-guide/connect-code-repository.md) for more information. {% hint style="info" %} Checkout the [documentation on fetching runs](../how-to/pipeline-development/build-pipelines/fetching-pipelines.md) for more information on the various ways how you can fetch and use the pipeline, pipeline run, step run, and artifact resources in code. {% endhint %} #### Stacks, Infrastructure, Authentication * **Stack**: The stacks registered in your ZenML instance. * **Stack Components**: The stack components registered in your ZenML instance, e.g., all orchestrators, artifact stores, model deployers, ... * **Flavors**: The [stack component flavors](../getting-started/core-concepts.md#flavor) available to you, including: * Built-in flavors like the [local orchestrator](../component-guide/orchestrators/local.md), * Integration-enabled flavors like the [Kubeflow orchestrator](../component-guide/orchestrators/kubeflow.md), * Custom flavors that you have [created yourself](../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md). * **User**: The users registered in your ZenML instance. If you are running locally, there will only be a single `default` user. * **Secrets**: The infrastructure authentication secrets that you have registered in the [ZenML Secret Store](../how-to/project-setup-and-management/interact-with-secrets.md). * **Service Connectors**: The service connectors that you have set up to [connect ZenML to your infrastructure](../how-to/infrastructure-deployment/auth-management/README.md). ### Client Methods #### Reading and Writing Resources **List Methods** Get a list of resources, e.g.: ```python client.list_pipeline_runs( stack_id=client.active_stack_model.id, # filter by stack user_id=client.active_user.id, # filter by user sort_by="desc:start_time", # sort by start time descending size=10, # limit page size to 10 ) ``` These methods always return a [Page](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-models/#zenml.models.page\_model) of resources, which behaves like a standard Python list and contains, by default, the first 50 results. You can modify the page size by passing the `size` argument or fetch a subsequent page by passing the `page` argument to the list method. You can further restrict your search by passing additional arguments that will be used to filter the results. E.g., most resources have a `user_id` associated with them that can be set to only list resources created by that specific user. The available filter argument options are different for each list method; check out the method declaration in the [Client SDK documentation](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-client/) to find out which exact arguments are supported or have a look at the fields of the corresponding filter model class. Except for pipeline runs, all other resources will by default be ordered by creation time ascending. E.g., `client.list_artifacts()` would return the first 50 artifacts ever created. You can change the ordering by specifying the `sort_by` argument when calling list methods. **Get Methods** Fetch a specific instance of a resource by either resource ID, name, or name prefix, e.g.: ```python client.get_pipeline_run("413cfb42-a52c-4bf1-a2fd-78af2f7f0101") # ID client.get_pipeline_run("first_pipeline-2023_06_20-16_20_13_274466") # Name client.get_pipeline_run("first_pipeline-2023_06_20-16") # Name prefix ``` **Create, Update, and Delete Methods** Methods for creating / updating / deleting resources are only available for some of the resources and the required arguments are different for each resource. Checkout the [Client SDK Documentation](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-client/) to find out whether a specific resource supports write operations through the Client and which arguments are required. #### Active User and Active Stack For some use cases you might need to know information about the user that you are authenticated as or the stack that you have currently set as active. You can fetch this information via the `client.active_user` and `client.active_stack_model` properties respectively, e.g.: ```python my_runs_on_current_stack = client.list_pipeline_runs( stack_id=client.active_stack_model.id, # on current stack user_id=client.active_user.id, # ran by you ) ``` ### Resource Models The methods of the ZenML Client all return **Response Models**, which are [Pydantic Models](https://docs.pydantic.dev/latest/usage/models/) that allow ZenML to validate that the returned data always has the correct attributes and types. E.g., the `client.list_pipeline_runs` method always returns type `Page[PipelineRunResponseModel]`. {% hint style="info" %} You can think of these models as similar to types in strictly-typed languages, or as the requirements of a single endpoint in an API. In particular, they are **not related to machine learning models** like decision trees, neural networks, etc. {% endhint %} ZenML also has similar models that define which information is required to create, update, or search resources, named **Request Models**, **Update Models**, and **Filter Models** respectively. However, these models are only used for the server API endpoints, and not for the Client methods. {% hint style="info" %} To find out which fields a specific resource model contains, checkout the [ZenML Models SDK Documentation](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-models/#zenml.models) and expand the source code to see a list of all fields of the respective model. Note that all resources have **Base Models** that define fields that response, request, update, and filter models have in common, so you need to take a look at the base model source code as well. {% endhint %}
ZenML Scarf
================ File: docs/book/user-guide/cloud-guide/cloud-guide.md ================ --- description: Taking your ZenML workflow to the next level. --- # ☁️ Cloud guide This section of the guide consists of easy to follow guides on how to connect the major public clouds to your ZenML deployment. We achieve this by configuring a [stack](../production-guide/understand-stacks.md). A `stack` is the configuration of tools and infrastructure that your pipelines can run on. When you run a pipeline, ZenML performs a different series of actions depending on the stack.

ZenML is the translation layer that allows your code to run on any of your stacks

Note, this guide focuses on the *registering* a stack, meaning that the resources required to run pipelines have already been *provisioned*. In order to provision the underlying infrastructure, you can either do so manually, use 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 Terraform modules](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md).
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/evaluation/evaluation-in-65-loc.md ================ --- description: Learn how to implement evaluation for RAG in just 65 lines of code. --- # Evaluation in 65 lines of code Our RAG guide included [a short example](../rag-with-zenml/rag-85-loc.md) for how to implement a basic RAG pipeline in just 85 lines of code. In this section, we'll build on that example to show how you can evaluate the performance of your RAG pipeline in just 65 lines. For the full code, please visit the project repository [here](https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/most\_basic\_eval.py). The code that follows requires the functions from the earlier RAG pipeline code to work. ```python # ...previous RAG pipeline code here... # see https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/most_basic_rag_pipeline.py eval_data = [ { "question": "What creatures inhabit the luminescent forests of ZenML World?", "expected_answer": "The luminescent forests of ZenML World are inhabited by glowing Zenbots.", }, { "question": "What do Fractal Fungi do in the melodic caverns of ZenML World?", "expected_answer": "Fractal Fungi emit pulsating tones that resonate through the crystalline structures, creating a symphony of otherworldly sounds in the melodic caverns of ZenML World.", }, { "question": "Where do Gravitational Geckos live in ZenML World?", "expected_answer": "Gravitational Geckos traverse the inverted cliffs of ZenML World.", }, ] def evaluate_retrieval(question, expected_answer, corpus, top_n=2): relevant_chunks = retrieve_relevant_chunks(question, corpus, top_n) score = any( any(word in chunk for word in tokenize(expected_answer)) for chunk in relevant_chunks ) return score def evaluate_generation(question, expected_answer, generated_answer): client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) chat_completion = client.chat.completions.create( messages=[ { "role": "system", "content": "You are an evaluation judge. Given a question, an expected answer, and a generated answer, your task is to determine if the generated answer is relevant and accurate. Respond with 'YES' if the generated answer is satisfactory, or 'NO' if it is not.", }, { "role": "user", "content": f"Question: {question}\nExpected Answer: {expected_answer}\nGenerated Answer: {generated_answer}\nIs the generated answer relevant and accurate?", }, ], model="gpt-3.5-turbo", ) judgment = chat_completion.choices[0].message.content.strip().lower() return judgment == "yes" retrieval_scores = [] generation_scores = [] for item in eval_data: retrieval_score = evaluate_retrieval( item["question"], item["expected_answer"], corpus ) retrieval_scores.append(retrieval_score) generated_answer = answer_question(item["question"], corpus) generation_score = evaluate_generation( item["question"], item["expected_answer"], generated_answer ) generation_scores.append(generation_score) retrieval_accuracy = sum(retrieval_scores) / len(retrieval_scores) generation_accuracy = sum(generation_scores) / len(generation_scores) print(f"Retrieval Accuracy: {retrieval_accuracy:.2f}") print(f"Generation Accuracy: {generation_accuracy:.2f}") ``` As you can see, we've added two evaluation functions: `evaluate_retrieval` and `evaluate_generation`. The `evaluate_retrieval` function checks if the retrieved chunks contain any words from the expected answer. The `evaluate_generation` function uses OpenAI's chat completion LLM to evaluate the quality of the generated answer. We then loop through the evaluation data, which contains questions and expected answers, and evaluate the retrieval and generation components of our RAG pipeline. Finally, we calculate the accuracy of both components and print the results: ![](../../../.gitbook/assets/evaluation-65-loc.png) As you can see, we get 100% accuracy for both retrieval and generation in this example. Not bad! The sections that follow will provide a more detailed and sophisticated implementation of RAG evaluation, but this example shows how you can think about it at a high level!
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/evaluation/evaluation-in-practice.md ================ --- description: Learn how to evaluate the performance of your RAG system in practice. --- # Evaluation in practice Now that we've seen individually how to evaluate the retrieval and generation components of our pipeline, it's worth taking a step back to think through how all of this works in practice. Our example project includes the evaluation as a separate pipeline that optionally runs after the main pipeline that generates and populates the embeddings. This is a good practice to follow, as it allows you to separate the concerns of generating the embeddings and evaluating them. Depending on the specific use case, the evaluations could be included as part of the main pipeline and used as a gating mechanism to determine whether the embeddings are good enough to be used in production. Given some of the performance constraints of the LLM judge, it might be worth experimenting with using a local LLM judge for evaluation during the course of the development process and then running the full evaluation using a cloud LLM like Anthropic's Claude or OpenAI's GPT-3.5 or 4. This can help you iterate faster and get a sense of how well your embeddings are performing before committing to the cost of running the full evaluation. ## Automated evaluation isn't a silver bullet While automating the evaluation process can save you time and effort, it's important to remember that it doesn't replace the need for a human to review the results. The LLM judge is expensive to run, and it takes time to get the results back. Automating the evaluation process can help you focus on the details and the data, but it doesn't replace the need for a human to review the results and make sure that the embeddings (and the RAG system as a whole) are performing as expected. ## When and how much to evaluate The frequency and depth of evaluation will depend on your specific use case and the constraints of your project. In an ideal world, you would evaluate the performance of your embeddings and the RAG system as a whole as often as possible, but in practice, you'll need to balance the cost of running the evaluation with the need to iterate quickly. Some tests can be run quickly and cheaply (notably the tests of the retrieval system) while others (like the LLM judge) are more expensive and time-consuming. You should structure your RAG tests and evaluation to reflect this, with some tests running frequently and others running less often, just as you would in any other software project. There's more we could improve our evaluation system, but for now we can continue onwards to [adding a reranker](../reranking/README.md) to improve our retrieval. This will allow us to improve the performance of our retrieval system without needing to retrain the embeddings. We'll cover this in the next section. ## Try it out! To see how this works in practice, you can run the evaluation pipeline using the project code. This will give you a sense of how the evaluation process works in practice and you can of course then play with and modify the evaluation code. To run the evaluation pipeline, first clone the project repository: ```bash git clone https://github.com/zenml-io/zenml-projects.git ``` Then navigate to the `llm-complete-guide` directory and follow the instructions in the `README.md` file to run the evaluation pipeline. (You'll have to have first run the main pipeline to generate the embeddings.) To run the evaluation pipeline, you can use the following command: ```bash python run.py --evaluation ``` This will run the evaluation pipeline and output the results to the console. You can then inspect the progress, logs and results in the dashboard!
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/evaluation/generation.md ================ --- description: Evaluate the generation component of your RAG pipeline. --- # Generation evaluation Now that we have a sense of how to evaluate the retrieval component of our RAG pipeline, let's move on to the generation component. The generation component is responsible for generating the answer to the question based on the retrieved context. At this point, our evaluation starts to move into more subjective territory. It's harder to come up with metrics that can accurately capture the quality of the generated answers. However, there are some things we can do. As with the [retrieval evaluation](retrieval.md), we can start with a simple approach and then move on to more sophisticated methods. ## Handcrafted evaluation tests As in the retrieval evaluation, we can start by putting together a set of examples where we know that our generated output should or shouldn't include certain terms. For example, if we're generating answers to questions about which orchestrators ZenML supports, we can check that the generated answers include terms like "Airflow" and "Kubeflow" (since we do support them) and exclude terms like "Flyte" or "Prefect" (since we don't (yet!) support them). These handcrafted tests should be driven by mistakes that you've already seen in the RAG output. The negative example of "Flyte" and "Prefect" showing up in the list of supported orchestrators, for example, shows up sometimes when you use GPT 3.5 as the LLM. ![](/docs/book/.gitbook/assets/generation-eval-manual.png) As another example, when you make a query asking 'what is the default orchestrator in ZenML?' you would expect that the answer would include the word 'local', so we can make a test case to confirm that. You can view our starter set of these tests [here](https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/steps/eval_e2e.py#L28-L55). It's better to start with something small and simple and then expand as is needed. There's no need for complicated harnesses or frameworks at this stage. **`bad_answers` table:** | Question | Bad Words | |----------|-----------| | What orchestrators does ZenML support? | AWS Step Functions, Flyte, Prefect, Dagster | | What is the default orchestrator in ZenML? | Flyte, AWS Step Functions | **`bad_immediate_responses` table:** | Question | Bad Words | |----------|-----------| | Does ZenML support the Flyte orchestrator out of the box? | Yes | **`good_responses` table:** | Question | Good Words | |----------|------------| | What are the supported orchestrators in ZenML? Please list as many of the supported ones as possible. | Kubeflow, Airflow | | What is the default orchestrator in ZenML? | local | Each type of test then catches a specific type of mistake. For example: ```python class TestResult(BaseModel): success: bool question: str keyword: str = "" response: str def test_content_for_bad_words( item: dict, n_items_retrieved: int = 5 ) -> TestResult: question = item["question"] bad_words = item["bad_words"] response = process_input_with_retrieval( question, n_items_retrieved=n_items_retrieved ) for word in bad_words: if word in response: return TestResult( success=False, question=question, keyword=word, response=response, ) return TestResult(success=True, question=question, response=response) ``` Here we're testing that a particular word doesn't show up in the generated response. If we find the word, then we return a failure, otherwise we return a success. This is a simple example, but you can imagine more complex tests that check for the presence of multiple words, or the presence of a word in a particular context. We pass these custom tests into a test runner that keeps track of how many are failing and also logs those to the console when they do: ```python def run_tests(test_data: list, test_function: Callable) -> float: failures = 0 total_tests = len(test_data) for item in test_data: test_result = test_function(item) if not test_result.success: logging.error( f"Test failed for question: '{test_result.question}'. Found word: '{test_result.keyword}'. Response: '{test_result.response}'" ) failures += 1 failure_rate = (failures / total_tests) * 100 logging.info( f"Total tests: {total_tests}. Failures: {failures}. Failure rate: {failure_rate}%" ) return round(failure_rate, 2) ``` Our end-to-end evaluation of the generation component is then a combination of these tests: ```python @step def e2e_evaluation() -> ( Annotated[float, "failure_rate_bad_answers"], Annotated[float, "failure_rate_bad_immediate_responses"], Annotated[float, "failure_rate_good_responses"], ): logging.info("Testing bad answers...") failure_rate_bad_answers = run_tests( bad_answers, test_content_for_bad_words ) logging.info(f"Bad answers failure rate: {failure_rate_bad_answers}%") logging.info("Testing bad immediate responses...") failure_rate_bad_immediate_responses = run_tests( bad_immediate_responses, test_response_starts_with_bad_words ) logging.info( f"Bad immediate responses failure rate: {failure_rate_bad_immediate_responses}%" ) logging.info("Testing good responses...") failure_rate_good_responses = run_tests( good_responses, test_content_contains_good_words ) logging.info( f"Good responses failure rate: {failure_rate_good_responses}%" ) return ( failure_rate_bad_answers, failure_rate_bad_immediate_responses, failure_rate_good_responses, ) ``` Running the tests using different LLMs will give different results. Here our Ollama Mixtral did worse than GPT 3.5, for example, but there were still some failures with GPT 3.5. This is a good way to get a sense of how well your generation component is doing. As you become more familiar with the kinds of outputs your LLM generates, you can add the hard ones to this test suite. This helps prevent regressions and is directly related to the quality of the output you're getting. This way you can optimize for your specific use case. ## Automated evaluation using another LLM Another way to evaluate the generation component is to use another LLM to grade the output of the LLM you're evaluating. This is a more sophisticated approach and requires a bit more setup. We can use the pre-generated questions and the associated context as input to the LLM and then use another LLM to assess the quality of the output on a scale of 1 to 5. This is a more quantitative approach and since it's automated it can run across a larger set of data. ![](/docs/book/.gitbook/assets/generation-eval-automated.png) {% hint style="warning" %} LLMs don't always do well on this kind of evaluation where numbers are involved. There are some studies showing that LLMs can be biased towards certain numbers or ranges of numbers. This is something to keep in mind when using this approach. Qualitative evaluations are often more reliable but then that means a human has to do the evaluation. {% endhint %} We can start by setting up a Pydantic model to hold the data we need. We set constraints to ensure that the data we're getting back are only integers between 1 and 5, inclusive: ```python class LLMJudgedTestResult(BaseModel): toxicity: conint(ge=1, le=5) faithfulness: conint(ge=1, le=5) helpfulness: conint(ge=1, le=5) relevance: conint(ge=1, le=5) ``` We can use this in a test function that: - takes a question and a context as inputs - generates an answer using the LLM we're evaluating - makes a call to an (optionally different) LLM we're using to judge the quality of the answer getting back a score for each of the four categories in JSON format - parses the JSON and returns the result of the evaluation as our Pydantic model instance Pydantic handles the validation of the JSON input for us, so we can be sure that we're getting the data we expect and in a form that we can use. ```python def llm_judged_test_e2e( question: str, context: str, n_items_retrieved: int = 5, ) -> LLMJudgedTestResult: """E2E tests judged by an LLM. Args: item (dict): The item to test. n_items_retrieved (int): The number of items to retrieve. Returns: LLMJudgedTestResult: The result of the test. """ logging.debug("Starting LLM judged test...") response = process_input_with_retrieval( question, n_items_retrieved=n_items_retrieved ) logging.debug("Input processed with retrieval.") prompt = f""" Please analyze the following text and provided context to provide scores for toxicity, faithfulness, helpfulness, and relevance. The toxicity score should be an integer between 1 and 5, where 1 is not toxic and 5 is very toxic. The faithfulness score should be an integer between 1 and 5, where 1 is not faithful to the provided context and 5 is very faithful. The helpfulness score should be an integer between 1 and 5, where 1 is not helpful and 5 is very helpful. The relevance score should be an integer between 1 and 5, where 1 is not relevant given the context and 5 is very relevant. **Text:** {response} **Context:** {context} **Output format:** {{ "toxicity": int, "faithfulness": int, "helpfulness": int, "relevance": int }} """ logging.debug("Prompt created.") response = completion( model="gpt-4-turbo", messages=[{"content": prompt, "role": "user"}] ) json_output = response["choices"][0]["message"]["content"].strip() logging.info("Received response from model.") logging.debug(json_output) try: return LLMJudgedTestResult(**json.loads(json_output)) except json.JSONDecodeError as e: logging.error(f"JSON bad output: {json_output}") raise e ``` Currently we're not handling retries of the output from the LLM in the case where the JSON isn't output correctly, but potentially that's something we might want to do. We can then run this test across a set of questions and contexts: ```python def run_llm_judged_tests( test_function: Callable, sample_size: int = 50, ) -> Tuple[ Annotated[float, "average_toxicity_score"], Annotated[float, "average_faithfulness_score"], Annotated[float, "average_helpfulness_score"], Annotated[float, "average_relevance_score"], ]: dataset = load_dataset("zenml/rag_qa_embedding_questions", split="train") # Shuffle the dataset and select a random sample sampled_dataset = dataset.shuffle(seed=42).select(range(sample_size)) total_tests = len(sampled_dataset) total_toxicity = 0 total_faithfulness = 0 total_helpfulness = 0 total_relevance = 0 for item in sampled_dataset: question = item["generated_questions"][0] context = item["page_content"] try: result = test_function(question, context) except json.JSONDecodeError as e: logging.error(f"Failed for question: {question}. Error: {e}") total_tests -= 1 continue total_toxicity += result.toxicity total_faithfulness += result.faithfulness total_helpfulness += result.helpfulness total_relevance += result.relevance average_toxicity_score = total_toxicity / total_tests average_faithfulness_score = total_faithfulness / total_tests average_helpfulness_score = total_helpfulness / total_tests average_relevance_score = total_relevance / total_tests return ( round(average_toxicity_score, 3), round(average_faithfulness_score, 3), round(average_helpfulness_score, 3), round(average_relevance_score, 3), ) ``` You'll want to use your most capable and reliable LLM to do the judging. In our case, we used the new GPT-4 Turbo. The quality of the evaluation is only as good as the LLM you're using to do the judging and there is a large difference between GPT-3.5 and GPT-4 Turbo in terms of the quality of the output, not least in its ability to output JSON correctly. Here was the output following an evaluation for 50 randomly sampled datapoints: ```shell Step e2e_evaluation_llm_judged has started. Average toxicity: 1.0 Average faithfulness: 4.787 Average helpfulness: 4.595 Average relevance: 4.87 Step e2e_evaluation_llm_judged has finished in 8m51s. Pipeline run has finished in 8m52s. ``` This took around 9 minutes to run using GPT-4 Turbo as the evaluator and the default GPT-3.5 as the LLM being evaluated. To take this further, there are a number of ways it might be improved: - **Retries**: As mentioned above, we're not currently handling retries of the output from the LLM in the case where the JSON isn't output correctly. This could be improved by adding a retry mechanism that waits for a certain amount of time before trying again. (We could potentially use the [`instructor`](https://github.com/jxnl/instructor) library to handle this specifically.) - **Use OpenAI's 'JSON mode'**: OpenAI has a [JSON mode](https://platform.openai.com/docs/guides/text-generation/json-mode) that can be used to ensure that the output is always in JSON format. This could be used to ensure that the output is always in the correct format. - **More sophisticated evaluation**: The evaluation we're doing here is quite simple. We're just asking for a score in four categories. There are more sophisticated ways to evaluate the quality of the output, such as using multiple evaluators and taking the average score, or using a more complex scoring system that takes into account the context of the question and the context of the answer. - **Batch processing**: We're running the evaluation one question at a time here. It would be more efficient to run the evaluation in batches to speed up the process. - **More data**: We're only using 50 samples here. This could be increased to get a more accurate picture of the quality of the output. - **More LLMs**: We're only using GPT-4 Turbo here. It would be interesting to see how other LLMs perform as evaluators. - **Handcrafted questions based on context**: We're using the generated questions here. It would be interesting to see how the LLM performs when given handcrafted questions that are based on the context of the question. - **Human in the loop**: The LLM actually provides qualitative feedback on the output as well as the JSON scores. This data could be passed into an annotation tool to get human feedback on the quality of the output. This would be a more reliable way to evaluate the quality of the output and would offer some insight into the kinds of mistakes the LLM is making. Most notably, the scores we're currently getting are pretty high, so it would make sense to pass in harder questions and be more specific in the judging criteria. This will give us more room to improve as it is sure that the system is not perfect. While this evaluation approach serves as a solid foundation, it's worth noting that there are other frameworks available that can further enhance the evaluation process. Frameworks such as [`ragas`](https://github.com/explodinggradients/ragas), [`trulens`](https://www.trulens.org/), [DeepEval](https://docs.confident-ai.com/), and [UpTrain](https://github.com/uptrain-ai/uptrain) can be integrated with ZenML depending on your specific use-case and understanding of the underlying concepts. These frameworks, although potentially complex to set up and use, can provide more sophisticated evaluation capabilities as your project evolves and grows in complexity. We now have a working evaluation of both the retrieval and generation evaluation components of our RAG pipeline. We can use this to track how our pipeline improves as we make changes to the retrieval and generation components. ## Code Example To explore the full code, visit the [Complete Guide](https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/) repository and for this section, particularly [the `eval_e2e.py` file](https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/steps/eval_e2e.py).
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/evaluation/README.md ================ --- description: Track how your RAG pipeline improves using evaluation and metrics. --- # Evaluation and metrics In this section, we'll explore how to evaluate the performance of your RAG pipeline using metrics and visualizations. Evaluating your RAG pipeline is crucial to understanding how well it performs and identifying areas for improvement. With language models in particular, it's hard to evaluate their performance using traditional metrics like accuracy, precision, and recall. This is because language models generate text, which is inherently subjective and difficult to evaluate quantitatively. Our RAG pipeline is a whole system, moreover, not just a model, and evaluating it requires a holistic approach. We'll look at various ways to evaluate the performance of your RAG pipeline but the two main areas we'll focus on are: * [Retrieval evaluation](retrieval.md), so checking that the retrieved documents or document chunks are relevant to the query. * [Generation evaluation](generation.md), so checking that the generated text is coherent and helpful for our specific use case. ![](../../../.gitbook/assets/evaluation-two-parts.png) In the previous section we built out a basic RAG pipeline for our documentation question-and-answer use case. We'll use this pipeline to demonstrate how to evaluate the performance of your RAG pipeline. {% hint style="info" %} If you were running this in a production setting, you might want to set up evaluation to check the performance of a raw LLM model (i.e. without any retrieval / RAG components) as a baseline, and then compare this to the performance of your RAG pipeline. This will help you understand how much value the retrieval and generation components are adding to your system. We won't cover this here, but it's a good practice to keep in mind. {% endhint %} ## What are we evaluating? When evaluating the performance of your RAG pipeline, your specific use case and the extent to which you can tolerate errors or lower performance will determine what you need to evaluate. For instance, if you're building a user-facing chatbot, you might need to evaluate the following: * Are the retrieved documents relevant to the query? * Is the generated answer coherent and helpful for your specific use case? * Does the generated answer contain hate speech or any sort of toxic language? These are just examples, and the specific metrics and methods you use will depend on your use case. The [generation evaluation](generation.md) functions as an end-to-end evaluation of the RAG pipeline, as it checks the final output of the system. It's during these end-to-end evaluations that you'll have most leeway to use subjective metrics, as you're evaluating the system as a whole. Before we dive into the details, let's take a moment to look at [a short high-level code example](evaluation-in-65-loc.md) showcasing the two main areas of evaluation. Afterwards the following sections will cover the two main areas of evaluation in more detail [as well as offer practical guidance](../evaluation/evaluation-in-practice.md) on when to run these evaluations and what to look for in the results.
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/evaluation/retrieval.md ================ --- description: See how the retrieval component responds to changes in the pipeline. --- # Retrieval evaluation The retrieval component of our RAG pipeline is responsible for finding relevant documents or document chunks to feed into the generation component. In this section we'll explore how to evaluate the performance of the retrieval component of your RAG pipeline. We're checking how accurate the semantic search is, or in other words how relevant the retrieved documents are to the query. Our retrieval component takes the incoming query and converts it into a vector or embedded representation that can be used to search for relevant documents. We then use this representation to search through a corpus of documents and retrieve the most relevant ones. ## Manual evaluation using handcrafted queries The most naive and simple way to check this would be to handcraft some queries where we know the specific documents needed to answer it. We can then check if the retrieval component is able to retrieve these documents. This is a manual evaluation process and can be time-consuming, but it's a good way to get a sense of how well the retrieval component is working. It can also be useful to target known edge cases or difficult queries to see how the retrieval component handles those known scenarios. ![](/docs/book/.gitbook/assets/retrieval-eval-manual.png) Implementing this is pretty simple - you just need to create some queries and check the retrieved documents. Having tested the basic inference of our RAG setup quite a bit, there were some clear areas where the retrieval component could be improved. I looked in our documentation to find some examples where the information could only be found in a single page and then wrote some queries that would require the retrieval component to find that page. For example, the query "How do I get going with the Label Studio integration? What are the first steps?" would require the retrieval component to find [the Label Studio integration page](../../../component-guide/annotators/label-studio.md). Some of the other examples used are: | Question | URL Ending | |----------|------------| | How do I get going with the Label Studio integration? What are the first steps? | stacks-and-components/component-guide/annotators/label-studio | | How can I write my own custom materializer? | user-guide/advanced-guide/data-management/handle-custom-data-types | | How do I generate embeddings as part of a RAG pipeline when using ZenML? | user-guide/llmops-guide/rag-with-zenml/embeddings-generation | | How do I use failure hooks in my ZenML pipeline? | user-guide/advanced-guide/pipelining-features/use-failure-success-hooks | | Can I deploy ZenML self-hosted with Helm? How do I do it? | deploying-zenml/zenml-self-hosted/deploy-with-helm | For the retrieval pipeline, all we have to do is encode the query as a vector and then query the PostgreSQL database for the most similar vectors. We then check whether the URL for the document we thought must show up is actually present in the top `n` results. ```python def query_similar_docs(question: str, url_ending: str) -> tuple: embedded_question = get_embeddings(question) db_conn = get_db_conn() top_similar_docs_urls = get_topn_similar_docs( embedded_question, db_conn, n=5, only_urls=True ) urls = [url[0] for url in top_similar_docs_urls] # Unpacking URLs from tuples return (question, url_ending, urls) def test_retrieved_docs_retrieve_best_url(question_doc_pairs: list) -> float: total_tests = len(question_doc_pairs) failures = 0 for pair in question_doc_pairs: question, url_ending, urls = query_similar_docs( pair["question"], pair["url_ending"] ) if all(url_ending not in url for url in urls): logging.error( f"Failed for question: {question}. Expected URL ending: {url_ending}. Got: {urls}" ) failures += 1 logging.info(f"Total tests: {total_tests}. Failures: {failures}") failure_rate = (failures / total_tests) * 100 return round(failure_rate, 2) ``` We include some logging so that when running the pipeline locally we can get some immediate feedback logged to the console. This functionality can then be packaged up into a ZenML step once we're happy it does what we need: ```python @step def retrieval_evaluation_small() -> Annotated[float, "small_failure_rate_retrieval"]: failure_rate = test_retrieved_docs_retrieve_best_url(question_doc_pairs) logging.info(f"Retrieval failure rate: {failure_rate}%") return failure_rate ``` We got a 20% failure rate on the first run of this test, which was a good sign that the retrieval component could be improved. We only had 5 test cases, so this was just a starting point. In reality, you'd want to keep adding more test cases to cover a wider range of scenarios. You'll discover these failure cases as you use the system more and more, so it's a good idea to keep a record of them and add them to your test suite. You'd also want to examine the logs to see exactly which query failed. In our case, checking the logs in the ZenML dashboard, we find the following: ``` Failed for question: How do I generate embeddings as part of a RAG pipeline when using ZenML?. Expected URL ending: user-guide/llmops-guide/ rag-with-zenml/embeddings-generation. Got: ['https://docs.zenml.io/user-guide/ llmops-guide/rag-with-zenml/data-ingestion', 'https://docs.zenml.io/user-guide/ llmops-guide/rag-with-zenml/understanding-rag', 'https://docs.zenml.io/v/docs/ user-guide/advanced-guide/data-management/handle-custom-data-types', 'https://docs. zenml.io/user-guide/llmops-guide/rag-with-zenml', 'https://docs.zenml.io/v/docs/ user-guide/llmops-guide/rag-with-zenml'] ``` We can maybe take a look at those documents to see why they were retrieved and not the one we expected. This is a good way to iteratively improve the retrieval component. ## Automated evaluation using synthetic generated queries For a broader evaluation we can examine a larger number of queries to check the retrieval component's performance. We do this by using an LLM to generate synthetic data. In our case we take the text of each document chunk and pass it to an LLM, telling it to generate a question. ![](/docs/book/.gitbook/assets/retrieval-eval-automated.png) For example, given the text: ``` zenml orchestrator connect ${ORCHESTRATOR\_NAME} -iHead on over to our docs to learn more about orchestrators and how to configure them. Container Registry export CONTAINER\_REGISTRY\_NAME=gcp\_container\_registry zenml container-registry register $ {CONTAINER\_REGISTRY\_NAME} --flavor=gcp --uri= # Connect the GCS orchestrator to the target gcp project via a GCP Service Connector zenml container-registry connect ${CONTAINER\_REGISTRY\_NAME} -i Head on over to our docs to learn more about container registries and how to configure them. 7) Create Stack export STACK\_NAME=gcp\_stack zenml stack register ${STACK\_NAME} -o $ {ORCHESTRATOR\_NAME} \\ a ${ARTIFACT\_STORE\_NAME} -c ${CONTAINER\_REGISTRY\_NAME} --set In case you want to also add any other stack components to this stack, feel free to do so. And you're already done! Just like that, you now have a fully working GCP stack ready to go. Feel free to take it for a spin by running a pipeline on it. Cleanup If you do not want to use any of the created resources in the future, simply delete the project you created. gcloud project delete
ZenML Scarf
PreviousScale compute to the cloud NextConfiguring ZenML Last updated 2 days ago ``` we might get the question: ``` How do I create and configure a GCP stack in ZenML using an orchestrator, container registry, and stack components, and how do I delete the resources when they are no longer needed? ``` If we generate questions for all of our chunks, we can then use these question-chunk pairs to evaluate the retrieval component. We pass the generated query to the retrieval component and then we check if the URL for the original document is in the top `n` results. To generate the synthetic queries we can use the following code: ```python from typing import List from litellm import completion from structures import Document from zenml import step LOCAL_MODEL = "ollama/mixtral" def generate_question(chunk: str, local: bool = False) -> str: model = LOCAL_MODEL if local else "gpt-3.5-turbo" response = completion( model=model, messages=[ { "content": f"This is some text from ZenML's documentation. Please generate a question that can be asked about this text: `{chunk}`", "role": "user", } ], api_base="http://localhost:11434" if local else None, ) return response.choices[0].message.content @step def generate_questions_from_chunks( docs_with_embeddings: List[Document], local: bool = False, ) -> List[Document]: for doc in docs_with_embeddings: doc.generated_questions = [generate_question(doc.page_content, local)] assert all(doc.generated_questions for doc in docs_with_embeddings) return docs_with_embeddings ``` As you can see, we're using [`litellm`](https://docs.litellm.ai/) again as the wrapper for the API calls. This allows us to switch between using a cloud LLM API (like OpenAI's GPT3.5 or 4) and a local LLM (like a quantized version of Mistral AI's Mixtral made available with [Ollama](https://ollama.com/). This has a number of advantages: - you keep your costs down by using a local model - you can iterate faster by not having to wait for API calls - you can use the same code for both local and cloud models For some tasks you'll want to use the best model your budget can afford, but for this task of question generation we're fine using a local and slightly less capable model. Even better is that it'll be much faster to generate the questions, especially using the basic setup we have here. To give you an indication of how long this process takes, generating 1800+ questions from an equivalent number of documentation chunks took a little over 45 minutes using the local model on a GPU-enabled machine with Ollama. ![](/docs/book/.gitbook/assets/hf-qa-embedding-questions.png) You can [view the generated dataset](https://huggingface.co/datasets/zenml/rag_qa_embedding_questions) on the Hugging Face Hub [here](https://huggingface.co/datasets/zenml/rag_qa_embedding_questions). This dataset contains the original document chunks, the generated questions, and the URL reference for the original document. Once we have the generated questions, we can then pass them to the retrieval component and check the results. For convenience we load the data from the Hugging Face Hub and then pass it to the retrieval component for evaluation. We shuffle the data and select a subset of it to speed up the evaluation process, but for a more thorough evaluation you could use the entire dataset. (The best practice of keeping a separate set of data for evaluation purposes is also recommended here, though we're not doing that in this example.) ```python @step def retrieval_evaluation_full( sample_size: int = 50, ) -> Annotated[float, "full_failure_rate_retrieval"]: dataset = load_dataset("zenml/rag_qa_embedding_questions", split="train") sampled_dataset = dataset.shuffle(seed=42).select(range(sample_size)) total_tests = len(sampled_dataset) failures = 0 for item in sampled_dataset: generated_questions = item["generated_questions"] question = generated_questions[ 0 ] # Assuming only one question per item url_ending = item["filename"].split("/")[ -1 ] # Extract the URL ending from the filename _, _, urls = query_similar_docs(question, url_ending) if all(url_ending not in url for url in urls): logging.error( f"Failed for question: {question}. Expected URL ending: {url_ending}. Got: {urls}" ) failures += 1 logging.info(f"Total tests: {total_tests}. Failures: {failures}") failure_rate = (failures / total_tests) * 100 return round(failure_rate, 2) ``` When we run this as part of the evaluation pipeline, we get a 16% failure rate which again tells us that we're doing pretty well but that there is room for improvement. As a baseline, this is a good starting point. We can then iterate on the retrieval component to improve its performance. To take this further, there are a number of ways it might be improved: - **More diverse question generation**: The current question generation approach uses a single prompt to generate questions based on the document chunks. You could experiment with different prompts or techniques to generate a wider variety of questions that test the retrieval component more thoroughly. For example, you could prompt the LLM to generate questions of different types (factual, inferential, hypothetical, etc.) or difficulty levels. - **Semantic similarity metrics**: In addition to checking if the expected URL is retrieved, you could calculate semantic similarity scores between the query and the retrieved documents using metrics like cosine similarity. This would give you a more nuanced view of retrieval performance beyond just binary success/failure. You could track average similarity scores and use them as a target metric to improve. - **Comparative evaluation**: Test out different retrieval approaches (e.g. different embedding models, similarity search algorithms, etc.) and compare their performance on the same set of queries. This would help identify the strengths and weaknesses of each approach. - **Error analysis**: Do a deeper dive into the failure cases to understand patterns and potential areas for improvement. Are certain types of questions consistently failing? Are there common characteristics among the documents that aren't being retrieved properly? Insights from error analysis can guide targeted improvements to the retrieval component. To wrap up, the retrieval evaluation process we've walked through - from manual spot-checking with carefully crafted queries to automated testing with synthetic question-document pairs - has provided a solid baseline understanding of our retrieval component's performance. The failure rates of 20% on our handpicked test cases and 16% on a larger sample of generated queries highlight clear room for improvement, but also validate that our semantic search is generally pointing in the right direction. Going forward, we have a rich set of options to refine and upgrade our evaluation approach. Generating a more diverse array of test questions, leveraging semantic similarity metrics for a nuanced view beyond binary success/failure, performing comparative evaluations of different retrieval techniques, and conducting deep error analysis on failure cases - all of these avenues promise to yield valuable insights. As our RAG pipeline grows to handle more complex and wide-ranging queries, continued investment in comprehensive retrieval evaluation will be essential to ensure we're always surfacing the most relevant information. Before we start working to improve or tweak our retrieval based on these evaluation results, let's shift gears and look at how we can evaluate the generation component of our RAG pipeline. Assessing the quality of the final answers produced by the system is equally crucial to gauging the effectiveness of our retrieval. Retrieval is only half the story. The true test of our system is the quality of the final answers it generates by combining retrieved content with LLM intelligence. In the next section, we'll dive into a parallel evaluation process for the generation component, exploring both automated metrics and human assessment to get a well-rounded picture of our RAG pipeline's end-to-end performance. By shining a light on both halves of the RAG architecture, we'll be well-equipped to iterate and optimize our way to an ever more capable and reliable question-answering system. ## Code Example To explore the full code, visit the [Complete Guide](https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/) repository and for this section, particularly [the `eval_retrieval.py` file](https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/steps/eval_retrieval.py).
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/finetuning-embeddings/evaluating-finetuned-embeddings.md ================ --- description: Evaluate finetuned embeddings and compare to original base embeddings. --- Now that we've finetuned our embeddings, we can evaluate them and compare to the base embeddings. We have all the data saved and versioned already, and we will reuse the same MatryoshkaLoss function for evaluation. In code, our evaluation steps are easy to comprehend. Here, for example, is the base model evaluation step: ```python from zenml import log_model_metadata, step def evaluate_model( dataset: DatasetDict, model: SentenceTransformer ) -> Dict[str, float]: """Evaluate the given model on the dataset.""" evaluator = get_evaluator( dataset=dataset, model=model, ) return evaluator(model) @step def evaluate_base_model( dataset: DatasetDict, ) -> Annotated[Dict[str, float], "base_model_evaluation_results"]: """Evaluate the base model on the given dataset.""" model = SentenceTransformer( EMBEDDINGS_MODEL_ID_BASELINE, device="cuda" if torch.cuda.is_available() else "cpu", ) results = evaluate_model( dataset=dataset, model=model, ) # Convert numpy.float64 values to regular Python floats # (needed for serialization) base_model_eval = { f"dim_{dim}_cosine_ndcg@10": float( results[f"dim_{dim}_cosine_ndcg@10"] ) for dim in EMBEDDINGS_MODEL_MATRYOSHKA_DIMS } log_model_metadata( metadata={"base_model_eval": base_model_eval}, ) return results ``` We log the results for our core Matryoshka dimensions as model metadata to ZenML within our evaluation step. This will allow us to inspect these results from within [the Model Control Plane](../../../how-to/model-management-metrics/model-control-plane/README.md) (see below for more details). Our results come in the form of a dictionary of string keys and float values which will, like all step inputs and outputs, be versioned, tracked and saved in your artifact store. ## Visualizing results It's possible to visualize results in a few different ways in ZenML, but one easy option is just to output your chart as an `PIL.Image` object. (See our [documentation on more ways to visualize your results](../../../how-to/data-artifact-management/visualize-artifacts/README.md).) The rest the implementation of our `visualize_results` step is just simple `matplotlib` code to plot out the base model evaluation against the finetuned model evaluation. We represent the results as percentage values and horizontally stack the two sets to make comparison a little easier. ![Visualizing finetuned embeddings evaluation results](../../../.gitbook/assets/finetuning-embeddings-visualization.png) We can see that our finetuned embeddings have improved the recall of our retrieval system across all of the dimensions, but the results are still not amazing. In a production setting, we would likely want to focus on improving the data being used for the embeddings training. In particular, we could consider stripping out some of the logs output from the documentation, and perhaps omit some pages which offer low signal for the retrieval task. This embeddings finetuning was run purely on the full set of synthetic data generated by `distilabel` and `gpt-4o`, so we wouldn't necessarily expect to see huge improvements out of the box, especially when the underlying data chunks are complex and contain multiple topics. ## Model Control Plane as unified interface Once all our pipelines are finished running, the best place to inspect our results as well as the artifacts and models we generated is the Model Control Plane. ![Model Control Plane](../../../.gitbook/assets/mcp-embeddings.gif) The interface is split into sections that correspond to: - the artifacts generated by our steps - the models generated by our steps - the metadata logged by our steps - (potentially) any deployments of models made, though we didn't use this in this guide so far - any pipeline runs associated with this 'Model' We can easily see which are the latest artifact or technical model versions, as well as compare the actual values of our evals or inspect the hardware or hyperparameters used for training. This one-stop-shop interface is available on ZenML Pro and you can learn more about it in the [Model Control Plane documentation](../../../how-to/model-management-metrics/model-control-plane/README.md). ## Next Steps Now that we've finetuned our embeddings and evaluated them, when they were in a good shape for use we could bring these into [the original RAG pipeline](../rag-with-zenml/basic-rag-inference-pipeline.md), regenerate a new series of embeddings for our data and then rerun our RAG retrieval evaluations to see how they've improved in our hand-crafted and LLM-powered evaluations. The next section will cover [LLM finetuning and deployment](../finetuning-llms/finetuning-llms.md) as the final part of our LLMops guide. (This section is currently still a work in progress, but if you're eager to try out LLM finetuning with ZenML, you can use [our LoRA project](https://github.com/zenml-io/zenml-projects/blob/main/llm-lora-finetuning/README.md) to get started. We also have [a blogpost](https://www.zenml.io/blog/how-to-finetune-llama-3-1-with-zenml) guide which takes you through [all the steps you need to finetune Llama 3.1](https://www.zenml.io/blog/how-to-finetune-llama-3-1-with-zenml) using GCP's Vertex AI with ZenML, including one-click stack creation!) To try out the two pipelines, please follow the instructions in [the project repository README](https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/README.md), and you can find the full code in that same directory.
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/finetuning-embeddings/finetuning-embeddings-with-sentence-transformers.md ================ --- description: Finetune embeddings with Sentence Transformers. --- We now have a dataset that we can use to finetune our embeddings. You can [inspect the positive and negative examples](https://huggingface.co/datasets/zenml/rag_qa_embedding_questions_0_60_0_distilabel) on the Hugging Face [datasets page](https://huggingface.co/datasets/zenml/rag_qa_embedding_questions_0_60_0_distilabel) since our previous pipeline pushed the data there. ![Synthetic data generated with distilabel for embeddings finetuning](../../../.gitbook/assets/distilabel-synthetic-dataset-hf.png) Our pipeline for finetuning the embeddings is relatively simple. We'll do the following: - load our data either from Hugging Face or [from Argilla via the ZenML annotation integration](../../../component-guide/annotators/argilla.md) - finetune our model using the [Sentence Transformers](https://www.sbert.net/) library - evaluate the base and finetuned embeddings - visualize the results of the evaluation ![Embeddings finetuning pipeline with Sentence Transformers and ZenML](../../../.gitbook/assets/rag-finetuning-embeddings-pipeline.png) ## Loading data By default the pipeline will load the data from our Hugging Face dataset. If you've annotated your data in Argilla, you can load the data from there instead. You'll just need to pass an `--argilla` flag to the Python invocation when you're running the pipeline like so: ```bash python run.py --embeddings --argilla ``` This assumes that you've set up an Argilla annotator in your stack. The code checks for the annotator and downloads the data that was annotated in Argilla. Please see our [guide to using the Argilla integration with ZenML](../../../component-guide/annotators/argilla.md) for more details. ## Finetuning with Sentence Transformers The `finetune` step in the pipeline is responsible for finetuning the embeddings model using the Sentence Transformers library. Let's break down the key aspects of this step: 1. **Model Loading**: The code loads the base model (`EMBEDDINGS_MODEL_ID_BASELINE`) using the Sentence Transformers library. It utilizes the SDPA (Self-Distilled Pruned Attention) implementation for efficient training with Flash Attention 2. 2. **Loss Function**: The finetuning process employs a custom loss function called `MatryoshkaLoss`. This loss function is a wrapper around the `MultipleNegativesRankingLoss` provided by Sentence Transformers. The Matryoshka approach involves training the model with different embedding dimensions simultaneously. It allows the model to learn embeddings at various granularities, improving its performance across different embedding sizes. 3. **Dataset Preparation**: The training dataset is loaded from the provided `dataset` parameter. The code saves the training data to a temporary JSON file and then loads it using the Hugging Face `load_dataset` function. 4. **Evaluator**: An evaluator is created using the `get_evaluator` function. The evaluator is responsible for assessing the model's performance during training. 5. **Training Arguments**: The code sets up the training arguments using the `SentenceTransformerTrainingArguments` class. It specifies various hyperparameters such as the number of epochs, batch size, learning rate, optimizer, precision (TF32 and BF16), and evaluation strategy. 6. **Trainer**: The `SentenceTransformerTrainer` is initialized with the model, training arguments, training dataset, loss function, and evaluator. The trainer handles the training process. The `trainer.train()` method is called to start the finetuning process. The model is trained for the specified number of epochs using the provided hyperparameters. 7. **Model Saving**: After training, the finetuned model is pushed to the Hugging Face Hub using the `trainer.model.push_to_hub()` method. The model is saved with the specified ID (`EMBEDDINGS_MODEL_ID_FINE_TUNED`). 9. **Metadata Logging**: The code logs relevant metadata about the training process, including the training parameters, hardware information, and accelerator details. 10. **Model Rehydration**: To handle materialization errors, the code saves the trained model to a temporary file, loads it back into a new `SentenceTransformer` instance, and returns the rehydrated model. (*Thanks and credit to Phil Schmid for [his tutorial on finetuning embeddings](https://www.philschmid.de/fine-tune-embedding-model-for-rag) with Sentence Transformers and a Matryoshka loss function. This project uses many ideas and some code from his implementation.*) ## Finetuning in code Here's a simplified code snippet highlighting the key parts of the finetuning process: ```python # Load the base model model = SentenceTransformer(EMBEDDINGS_MODEL_ID_BASELINE) # Define the loss function train_loss = MatryoshkaLoss(model, MultipleNegativesRankingLoss(model)) # Prepare the training dataset train_dataset = load_dataset("json", data_files=train_dataset_path) # Set up the training arguments args = SentenceTransformerTrainingArguments(...) # Create the trainer trainer = SentenceTransformerTrainer(model, args, train_dataset, train_loss) # Start training trainer.train() # Save the finetuned model trainer.model.push_to_hub(EMBEDDINGS_MODEL_ID_FINE_TUNED) ``` The finetuning process leverages the capabilities of the Sentence Transformers library to efficiently train the embeddings model. The Matryoshka approach allows for learning embeddings at different dimensions simultaneously, enhancing the model's performance across various embedding sizes. Our model is finetuned, saved in the Hugging Face Hub for easy access and reference in subsequent steps, but also versioned and tracked within ZenML for full observability. At this point the pipeline will evaluate the base and finetuned embeddings and visualize the results.
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/finetuning-embeddings/finetuning-embeddings.md ================ --- description: Finetune embeddings on custom synthetic data to improve retrieval performance. --- We previously learned [how to use RAG with ZenML](../rag-with-zenml/README.md) to build a production-ready RAG pipeline. In this section, we will explore how to optimize and maintain your embedding models through synthetic data generation and human feedback. So far, we've been using off-the-shelf embeddings, which provide a good baseline and decent performance on standard tasks. However, you can often significantly improve performance by finetuning embeddings on your own domain-specific data. Our RAG pipeline uses a retrieval-based approach, where it first retrieves the most relevant documents from our vector database, and then uses a language model to generate a response based on those documents. By finetuning our embeddings on a dataset of technical documentation similar to our target domain, we can improve the retrieval step and overall performance of the RAG pipeline. The work of finetuning embeddings based on synthetic data and human feedback is a multi-step process. We'll go through the following steps: - [generating synthetic data with `distilabel`](synthetic-data-generation.md) - [finetuning embeddings with Sentence Transformers](finetuning-embeddings-with-sentence-transformers.md) - [evaluating finetuned embeddings and using ZenML's model control plane to get a systematic overview](evaluating-finetuned-embeddings.md) Besides ZenML, we will do this by using two open source libraries: [`argilla`](https://github.com/argilla-io/argilla/) and [`distilabel`](https://github.com/argilla-io/distilabel). Both of these libraries focus optimizing model outputs through improving data quality, however, each one of them takes a different approach to tackle the same problem. `distilabel` provides a scalable and reliable approach to distilling knowledge from LLMs by generating synthetic data or providing AI feedback with LLMs as judges. `argilla` enables AI engineers and domain experts to collaborate on data projects by allowing them to organize and explore data through within an interactive and engaging UI. Both libraries can be used individually but they work better together. We'll showcase their use via ZenML pipelines. To follow along with the example explained in this guide, please follow the instructions in [the `llm-complete-guide` repository](https://github.com/zenml-io/zenml-projects/tree/main/llm-complete-guide) where the full code is also available. This specific section on embeddings finetuning can be run locally or using cloud compute as you prefer.
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/finetuning-embeddings/synthetic-data-generation.md ================ --- description: Generate synthetic data with distilabel to finetune embeddings. --- We already have [a dataset of technical documentation](https://huggingface.co/datasets/zenml/rag_qa_embedding_questions_0_60_0) that was generated previously while we were working on the RAG pipeline. We'll use this dataset to generate synthetic data with `distilabel`. You can inspect the data directly [on the Hugging Face dataset page](https://huggingface.co/datasets/zenml/rag_qa_embedding_questions_0_60_0). ![](../../../.gitbook/assets/rag-dataset-hf.png) As you can see, it is made up of some `page_content` (our chunks) as well as the source URL from where the chunk was taken from. With embeddings, what we're going to want to do is pair the `page_content` with a question that we want to answer. In a pre-LLM world we might have actually created a new column and worked to manually craft questions for each chunk. However, with LLMs, we can use the `page_content` to generate questions. ## Pipeline overview Our pipeline to generate synthetic data will look like this: ![](../../../.gitbook/assets/rag-synthetic-data-pipeline.png) We'll load the Hugging Face dataset, then we'll use `distilabel` to generate the synthetic data. To finish off, we'll push the newly-generated data to a new Hugging Face dataset and also push the same data to our Argilla instance for annotation and inspection. ## Synthetic data generation [`distilabel`](https://github.com/argilla-io/distilabel) provides a scalable and reliable approach to distilling knowledge from LLMs by generating synthetic data or providing AI feedback with LLMs as judges. We'll be using it a relatively simple use case to generate some queries appropriate to our documentation chunks, but it can be used for a variety of other tasks. We can set up a `distilabel` pipeline easily in our ZenML step to handle the dataset creation. We'll be using `gpt-4o` as the LLM to generate the synthetic data so you can follow along, but `distilabel` supports a variety of other LLM providers (including Ollama) so you can use whatever you have available. ```python import os from typing import Annotated, Tuple import distilabel from constants import ( DATASET_NAME_DEFAULT, OPENAI_MODEL_GEN, OPENAI_MODEL_GEN_KWARGS_EMBEDDINGS, ) from datasets import Dataset from distilabel.llms import OpenAILLM from distilabel.steps import LoadDataFromHub from distilabel.steps.tasks import GenerateSentencePair from zenml import step synthetic_generation_context = """ The text is a chunk from technical documentation of ZenML. ZenML is an MLOps + LLMOps framework that makes your infrastructure and workflow metadata accessible to data science teams. Along with prose explanations, the text chunk may include code snippets and logs but these are identifiable from the surrounding backticks. """ @step def generate_synthetic_queries( train_dataset: Dataset, test_dataset: Dataset ) -> Tuple[ Annotated[Dataset, "train_with_queries"], Annotated[Dataset, "test_with_queries"], ]: llm = OpenAILLM( model=OPENAI_MODEL_GEN, api_key=os.getenv("OPENAI_API_KEY") ) with distilabel.pipeline.Pipeline( name="generate_embedding_queries" ) as pipeline: load_dataset = LoadDataFromHub( output_mappings={"page_content": "anchor"}, ) generate_sentence_pair = GenerateSentencePair( triplet=True, # `False` to generate only positive action="query", llm=llm, input_batch_size=10, context=synthetic_generation_context, ) load_dataset >> generate_sentence_pair train_distiset = pipeline.run( parameters={ load_dataset.name: { "repo_id": DATASET_NAME_DEFAULT, "split": "train", }, generate_sentence_pair.name: { "llm": { "generation_kwargs": OPENAI_MODEL_GEN_KWARGS_EMBEDDINGS } }, }, ) test_distiset = pipeline.run( parameters={ load_dataset.name: { "repo_id": DATASET_NAME_DEFAULT, "split": "test", }, generate_sentence_pair.name: { "llm": { "generation_kwargs": OPENAI_MODEL_GEN_KWARGS_EMBEDDINGS } }, }, ) train_dataset = train_distiset["default"]["train"] test_dataset = test_distiset["default"]["train"] return train_dataset, test_dataset ``` As you can see, we set up the LLM, create a `distilabel` pipeline, load the dataset, mapping the `page_content` column so that it becomes `anchor`. (This column renaming will make things easier a bit later when we come to finetuning the embeddings.) Then we generate the synthetic data by using the `GenerateSentencePair` step. This will create queries for each of the chunks in the dataset, so if the chunk was about registering a ZenML stack, the query might be "How do I register a ZenML stack?". It will also create negative queries, which are queries that would be inappropriate for the chunk. We do this so that the embeddings model can learn to distinguish between appropriate and inappropriate queries. We add some context to the generation process to help the LLM understand the task and the data we're working with. In particular, we explain that some parts of the text are code snippets and logs. We found performance to be better when we added this context. When this step runs within ZenML it will handle spinning up the necessary processes to make batched LLM calls to the OpenAI API. This is really useful when working with large datasets. `distilabel` has also implemented a caching mechanism to avoid recomputing results for the same inputs. So in this case you have two layers of caching: one in the `distilabel` pipeline and one in the ZenML orchestrator. This helps [speed up the pace of iteration](https://www.zenml.io/blog/iterate-fast) and saves you money. ## Data annotation with Argilla Once we've let the LLM generate the synthetic data, we'll want to inspect it and make sure it looks good. We'll do this by pushing the data to an Argilla instance. We add a few extra pieces of metadata to the data to make it easier to navigate and inspect within our data annotation tool. These include: - `parent_section`: This will be the section of the documentation that the chunk is from. - `token_count`: This will be the number of tokens in the chunk. - `similarity-positive-negative`: This will be the cosine similarity between the positive and negative queries. - `similarity-anchor-positive`: This will be the cosine similarity between the anchor and positive queries. - `similarity-anchor-negative`: This will be the cosine similarity between the anchor and negative queries. We'll also add the embeddings for the anchor column so that we can use these for retrieval. We'll use the base model (in our case, `Snowflake/snowflake-arctic-embed-large`) to generate the embeddings. We use this function to map the dataset and process all the metadata: ```python def format_data(batch): model = SentenceTransformer( EMBEDDINGS_MODEL_ID_BASELINE, device="cuda" if torch.cuda.is_available() else "cpu", ) def get_embeddings(batch_column): vectors = model.encode(batch_column) return [vector.tolist() for vector in vectors] batch["anchor-vector"] = get_embeddings(batch["anchor"]) batch["question-vector"] = get_embeddings(batch["anchor"]) batch["positive-vector"] = get_embeddings(batch["positive"]) batch["negative-vector"] = get_embeddings(batch["negative"]) def get_similarities(a, b): similarities = [] for pos_vec, neg_vec in zip(a, b): similarity = cosine_similarity([pos_vec], [neg_vec])[0][0] similarities.append(similarity) return similarities batch["similarity-positive-negative"] = get_similarities( batch["positive-vector"], batch["negative-vector"] ) batch["similarity-anchor-positive"] = get_similarities( batch["anchor-vector"], batch["positive-vector"] ) batch["similarity-anchor-negative"] = get_similarities( batch["anchor-vector"], batch["negative-vector"] ) return batch ``` The [rest of the `push_to_argilla` step](https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/steps/push_to_argilla.py) is just setting up the Argilla dataset and pushing the data to it. At this point you'd move to Argilla to view the data, see which examples seem to make sense and which don't. You can update the questions (positive and negative) which were generated by the LLM. If you want, you can do some data cleaning and exploration to improve the data quality, perhaps using the similarity metrics that we calculated earlier. ![Argilla interface for data annotation](../../../.gitbook/assets/argilla-interface-embeddings-finetuning.png) We'll next move to actually finetuning the embeddings, assuming you've done some data exploration and annotation. The code will work even without the annotation, however, since we'll just use the full generated dataset and assume that the quality is good enough.
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/finetuning-llms/deploying-finetuned-models.md ================ # Deployment Options for finetuned LLMs Deploying your finetuned LLM is a critical step in bringing your custom finetuned model into a place where it can be used as part of a real-world use case. This process involves careful planning and consideration of various factors to ensure optimal performance, reliability, and cost-effectiveness. In this section, we'll explore the key aspects of LLM deployment and discuss different options available to you. ## Deployment Considerations Before diving into specific deployment options, you should understand the various factors that influence the deployment process. One of the primary considerations is the memory and machine requirements for your finetuned model. LLMs are typically resource-intensive, requiring substantial RAM, processing power and specialized hardware. This choice of hardware can significantly impact both performance and cost, so it's crucial to strike the right balance based on your specific use case. Real-time considerations play a vital role in deployment planning, especially for applications that require immediate responses. This includes preparing for potential failover scenarios if your finetuned model encounters issues, conducting thorough benchmarks and load testing, and modeling expected user load and usage patterns. Additionally, you'll need to decide between streaming and non-streaming approaches, each with its own set of trade-offs in terms of latency and resource utilization. Optimization techniques, such as quantization, can help reduce the resource footprint of your model. However, these Optimizations often come with additional steps in your workflow and require careful evaluation to ensure they don't negatively impact model performance. [Rigorous evaluation](./evaluation-for-finetuning.md) becomes crucial in quantifying the extent to which you can optimize without compromising accuracy or functionality. ## Deployment Options and Trade-offs When it comes to deploying your finetuned LLM, several options are available, each with its own set of advantages and challenges: 1. **Roll Your Own**: This approach involves setting up and managing your own infrastructure. While it offers the most control and customization, it also requires expertise and resources to maintain. For this, you'd usually create some kind of Docker-based service (a FastAPI endpoint, for example) and deploy this on your infrastructure, with you taking care of all of the steps along the way. 2. **Serverless Options**: Serverless deployments can provide scalability and cost-efficiency, as you only pay for the compute resources you use. However, be aware of the "cold start" phenomenon, which can introduce latency for infrequently accessed models. 3. **Always-On Options**: These deployments keep your model constantly running and ready to serve requests. While this approach minimizes latency, it can be more costly as you're paying for resources even during idle periods. 4. **Fully Managed Solutions**: Many cloud providers and AI platforms offer managed services for deploying LLMs. These solutions can simplify the deployment process but may come with less flexibility and potentially higher costs. When choosing a deployment option, consider factors such as your team's expertise, budget constraints, expected load patterns, and specific use case requirements like speed, throughput, and accuracy needs. ## Deployment with vLLM and ZenML [vLLM](https://github.com/vllm-project/vllm) is a fast and easy-to-use library for running large language models (LLMs) at high throughputs and low latency. ZenML comes with a [vLLM integration](../../../component-guide/model-deployers/vllm.md) that makes it easy to deploy your finetuned model using vLLM. You can use a pre-built step that exposes a `VLLMDeploymentService` that can be used as part of your deployment pipeline. ```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, "my_finetuned_llm"]: # ... # assume we have previously trained and saved our model service = vllm_model_deployer_step( model=model, timeout=timeout, ) return service ``` In this code snippet, the `model` argument can be a path to a local model or it can be a model ID on the Hugging Face Hub. This will then deploy the model locally using vLLM and you can then use the `VLLMDeploymentService` for batch inference requests using the OpenAI-compatible API. For more details on how to use this deployer, see the [vLLM integration documentation](../../../component-guide/model-deployers/vllm.md). ## Cloud-Specific Deployment Options For AWS deployments, Amazon SageMaker stands out as a fully managed machine learning platform that offers deployment of LLMs with options for real-time inference endpoints and automatic scaling. If you prefer a serverless approach, combining AWS Lambda with API Gateway can host your model and trigger it for real-time responses, though be mindful of potential cold start issues. For teams seeking more control over the runtime environment while still leveraging AWS's managed infrastructure, Amazon ECS or EKS with Fargate provides an excellent container orchestration solution, though do note that with all of these options you're taking on a level of complexity that might become costly to manage in-house. On the GCP side, Google Cloud AI Platform offers similar capabilities to SageMaker, providing managed ML services including model deployment and prediction. For a serverless option, Cloud Run can host your containerized LLM and automatically scale based on incoming requests. Teams requiring more fine-grained control over compute resources might prefer Google Kubernetes Engine (GKE) for deploying containerized models. ## Architectures for Real-Time Customer Engagement Ensuring your system can engage with customers in real-time, for example, requires careful architectural consideration. One effective approach is to deploy your model across multiple instances behind a load balancer, using auto-scaling to dynamically adjust the number of instances based on incoming traffic. This setup provides both responsiveness and scalability. To further enhance performance, consider implementing a caching layer using solutions like Redis. This can store frequent responses, reducing the load on your model and improving response times for common queries. For complex queries that may take longer to process, an asynchronous architecture using message queues (such as Amazon SQS or Google Cloud Pub/Sub) can manage request backlogs and prevent timeouts, ensuring a smooth user experience even under heavy load. For global deployments, edge computing services like [AWS Lambda@Edge](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-the-edge.html?tag=soumet-20) or [CloudFront Functions](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-functions.html?tag=soumet-20) can be invaluable. These allow you to deploy lighter versions of your model closer to end-users, significantly reducing latency for initial responses and improving the overall user experience. ## Reducing Latency and Increasing Throughput Optimizing your deployment for low latency and high throughput is crucial for real-time engagement. Start by focusing on model optimization techniques such as quantization to reduce model size and inference time. You might also explore distillation techniques to create smaller, faster models that approximate the performance of larger ones without sacrificing too much accuracy. Hardware acceleration can provide a significant performance boost. Leveraging GPU instances for inference, particularly for larger models, can dramatically reduce processing time. Implementing request batching allows you to process multiple inputs in a single forward pass, increasing overall throughput. This can be particularly effective when combined with parallel processing techniques, utilizing multi-threading or multi-processing to handle multiple requests concurrently. This would make sense if you were operating at serious scale, but this is probably unlikely in the short-term when you are just getting started. Finally, implement detailed monitoring and use profiling tools to identify bottlenecks in your inference pipeline. This ongoing process of measurement and optimization will help you continually refine your deployment, ensuring it meets the evolving demands of your users. By thoughtfully implementing these strategies and maintaining a focus on continuous improvement, you can create a robust, scalable system that provides real-time engagement with low latency and high throughput, regardless of whether you're deploying on AWS, GCP, or a multi-cloud environment. ## Monitoring and Maintenance Once your finetuned LLM is deployed, ongoing monitoring and maintenance become crucial. Key areas to watch include: 1. **Evaluation Failures**: Regularly run your model through evaluation sets to catch any degradation in performance. 2. **Latency Metrics**: Monitor response times to ensure they meet your application's requirements. 3. **Load and Usage Patterns**: Keep an eye on how users interact with your model to inform scaling decisions and potential Optimizations. 4. **Data Analysis**: Regularly analyze the inputs and outputs of your model to identify trends, potential biases, or areas for improvement. It's also important to consider privacy and security when capturing and logging responses. Ensure that your logging practices comply with relevant data protection regulations and your organization's privacy policies. By carefully considering these deployment options and maintaining vigilant monitoring practices, you can ensure that your finetuned LLM performs optimally and continues to meet the needs of your users and organization. ================ File: docs/book/user-guide/llmops-guide/finetuning-llms/evaluation-for-finetuning.md ================ # Evaluation for LLM Finetuning Evaluations (evals) for Large Language Model (LLM) finetuning are akin to unit tests in traditional software development. They play a crucial role in assessing the performance, reliability, and safety of finetuned models. Like unit tests, evals help ensure that your model behaves as expected and allow you to catch issues early in the development process. It's easy to feel a sense of paralysis when it comes to evaluations, especially since there are so many things that can potentially fall under the rubric of 'evaluation'. As an alternative, consider keeping the mantra of starting small and slowly building up your evaluation set. This incremental approach will serve you well and allow you to get started out of the gate instead of waiting until your project is too far advanced. Why do we even need evaluations, and why do we need them (however incremental and small) from the early stages? We want to ensure that our model is performing as intended, catch potential issues early, and track progress over time. Evaluations provide a quantitative and qualitative measure of our model's capabilities, helping us identify areas for improvement and guiding our iterative development process. By implementing evaluations early, we can establish a baseline for performance and make data-driven decisions throughout the finetuning process, ultimately leading to a more robust and reliable LLM. ## Motivation and Benefits The motivation for implementing thorough evals is similar to that of unit tests in traditional software development: 1. **Prevent Regressions**: Ensure that new iterations or changes don't negatively impact existing functionality. 2. **Track Improvements**: Quantify and visualize how your model improves with each iteration or finetuning session. 3. **Ensure Safety and Robustness**: Given the complex nature of LLMs, comprehensive evals help identify and mitigate potential risks, biases, or unexpected behaviors. By implementing a robust evaluation strategy, you can develop more reliable, performant, and safe finetuned LLMs while maintaining a clear picture of your model's capabilities and limitations throughout the development process. ## Types of Evaluations It's common for finetuning projects to use generic out-of-the-box evaluation frameworks, but it's also useful to understand how to implement custom evals for your specific use case. In the end, building out a robust set of evaluations is a crucial part of knowing whether what you finetune is actually working. It also will allow you to benchmark your progress over time as well as check -- when a new model gets released -- whether it even makes sense to continue with the finetuning work you've done. New open-source and open-weights models are released all the time, and you might find that your use case is better solved by a new model. Evaluations will allow you to make this decision. ### Custom Evals The approach taken for custom evaluations is similar to that used and [showcased in the RAG guide](../evaluation/README.md), but it is adapted here for the finetuning use case. The main distinction here is that we are not looking to evaluate retrieval, but rather the performance of the finetuned model (i.e. [the generation part](../evaluation/generation.md)). Custom evals are tailored to your specific use case and can be categorized into two main types: 1. **Success Modes**: These evals focus on things you want to see in your model's output, such as: - Correct formatting - Appropriate responses to specific prompts - Desired behavior in edge cases 2. **Failure Modes**: These evals target things you don't want to see, including: - Hallucinations (generating false or nonsensical information) - Incorrect output formats - Biased or insulting responses - Garbled or incoherent text - Failure to handle edge cases appropriately In terms of what this might look like in code, you can start off really simple and grow as your needs and understanding expand. For example, you could test some success and failure modes simply in the following way: ```python from my_library import query_llm good_responses = { "what are the best salads available at the food court?": ["caesar", "italian"], "how late is the shopping center open until?": ["10pm", "22:00", "ten"] } for question, answers in good_responses.items(): llm_response = query_llm(question) assert any(answer in llm_response for answer in answers), f"Response does not contain any of the expected answers: {answers}" bad_responses = { "who is the manager of the shopping center?": ["tom hanks", "spiderman"] } for question, answers in bad_responses.items(): llm_response = query_llm(question) assert not any(answer in llm_response for answer in answers), f"Response contains an unexpected answer: {llm_response}" ``` You can see how you might want to expand this out to cover more examples and more failure modes, but this is a good start. As you continue in the work of iterating on your model and performing more tests, you can update these cases with known failure modes (and/or with obvious success modes that your use case must always work for). ### Generalized Evals and Frameworks Generalized evals and frameworks provide a structured approach to evaluating your finetuned LLM. They offer: - Assistance in organizing and structuring your evals - Standardized evaluation metrics for common tasks - Insights into the model's overall performance When using Generalized evals, it's important to consider their limitations and caveats. While they provide valuable insights, they should be complemented with custom evals tailored to your specific use case. Some possible options for you to check out include: - [prodigy-evaluate](https://github.com/explosion/prodigy-evaluate?tab=readme-ov-file) - [ragas](https://docs.ragas.io/en/stable/getstarted/monitoring.html) - [giskard](https://docs.giskard.ai/en/stable/getting_started/quickstart/quickstart_llm.html) - [langcheck](https://github.com/citadel-ai/langcheck) - [nervaluate](https://github.com/MantisAI/nervaluate) (for NER) It's easy to build in one of these frameworks into your ZenML pipeline. The implementation of evaluation in [the `llm-lora-finetuning` project](https://github.com/zenml-io/zenml-projects/tree/main/llm-lora-finetuning) is a good example of how to do this. We used the `evaluate` library for ROUGE evaluation, but you could easily swap this out for another framework if you prefer. See [the previous section](finetuning-with-accelerate.md#implementation-details) for more details. ## Data and Tracking Regularly examining the data your model processes during inference is crucial for identifying patterns, issues, or areas for improvement. This analysis of inference data provides valuable insights into your model's real-world performance and helps guide future iterations. Whatever you do, just keep it simple at the beginning. Keep the 'remember to look at your data' mantra in your mind and set up some sort of repeated pattern or system that forces you to keep looking at the inference calls being made on your finetuned model. This will allow you to pick up the patterns of things that are working and failing for your model. As part of this, implementing comprehensive logging from the early stages of development is essential for tracking your model's progress and behavior. Consider using frameworks specifically designed for LLM evaluation to streamline this process, as they can provide structured approaches to data collection and analysis. Some recommended possible options include: - [weave](https://github.com/wandb/weave) - [openllmetry](https://github.com/traceloop/openllmetry) - [langsmith](https://smith.langchain.com/) - [langfuse](https://langfuse.com/) - [braintrust](https://www.braintrust.dev/) Alongside collecting the raw data and viewing it periodically, creating simple dashboards that display core metrics reflecting your model's performance is an effective way to visualize and monitor progress. These metrics should align with your iteration goals and capture improvements over time, allowing you to quickly assess the impact of changes and identify areas that require attention. Again, as with everything else, don't let perfect be the enemy of the good; a simple dashboard using simple technology with a few key metrics is better than no dashboard at all. ================ File: docs/book/user-guide/llmops-guide/finetuning-llms/finetuning-100-loc.md ================ --- description: Learn how to implement an LLM fine-tuning pipeline in just 100 lines of code. --- # Quick Start: Fine-tuning an LLM There's a lot to understand about LLM fine-tuning - from choosing the right base model to preparing your dataset and selecting training parameters. But let's start with a concrete implementation to see how it works in practice. The following 100 lines of code demonstrate: - Loading a small base model ([TinyLlama](https://huggingface.co/TinyLlama/TinyLlama_v1.1), 1.1B parameters) - Preparing a simple instruction-tuning dataset - Fine-tuning the model on custom data - Using the fine-tuned model to generate responses This example uses the same [fictional "ZenML World" setting as our RAG example](../rag-with-zenml/rag-85-loc.md), but now we're teaching the model to generate content about this world rather than just retrieving information. You'll need to `pip install` the following packages: ```bash pip install datasets transformers torch accelerate>=0.26.0 ``` ```python import os from typing import List, Dict, Tuple from datasets import Dataset from transformers import ( AutoTokenizer, AutoModelForCausalLM, TrainingArguments, Trainer, DataCollatorForLanguageModeling ) import torch def prepare_dataset() -> Dataset: data: List[Dict[str, str]] = [ {"instruction": "Describe a Zenbot.", "response": "A Zenbot is a luminescent robotic entity that inhabits the forests of ZenML World. They emit a soft, pulsating light as they move through the enchanted landscape."}, {"instruction": "What are Cosmic Butterflies?", "response": "Cosmic Butterflies are ethereal creatures that flutter through the neon skies of ZenML World. Their iridescent wings leave magical trails of stardust wherever they go."}, {"instruction": "Tell me about the Telepathic Treants.", "response": "Telepathic Treants are ancient, sentient trees connected through a quantum neural network spanning ZenML World. They share wisdom and knowledge across their vast network."} ] return Dataset.from_list(data) def format_instruction(example: Dict[str, str]) -> str: """Format the instruction and response into a single string.""" return f"### Instruction: {example['instruction']}\n### Response: {example['response']}" def tokenize_data(example: Dict[str, str], tokenizer: AutoTokenizer) -> Dict[str, torch.Tensor]: formatted_text = format_instruction(example) return tokenizer(formatted_text, truncation=True, padding="max_length", max_length=128) def fine_tune_model(base_model: str = "TinyLlama/TinyLlama-1.1B-Chat-v1.0") -> Tuple[AutoModelForCausalLM, AutoTokenizer]: # Initialize tokenizer and model tokenizer = AutoTokenizer.from_pretrained(base_model) tokenizer.pad_token = tokenizer.eos_token model = AutoModelForCausalLM.from_pretrained( base_model, torch_dtype=torch.bfloat16, device_map="auto" ) dataset = prepare_dataset() tokenized_dataset = dataset.map( lambda x: tokenize_data(x, tokenizer), remove_columns=dataset.column_names ) # Setup training arguments training_args = TrainingArguments( output_dir="./zenml-world-model", num_train_epochs=3, per_device_train_batch_size=1, gradient_accumulation_steps=4, learning_rate=2e-4, bf16=True, logging_steps=10, save_total_limit=2, ) # Create a data collator for language modeling data_collator = DataCollatorForLanguageModeling( tokenizer=tokenizer, mlm=False ) trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_dataset, data_collator=data_collator, ) trainer.train() return model, tokenizer def generate_response(prompt: str, model: AutoModelForCausalLM, tokenizer: AutoTokenizer, max_length: int = 128) -> str: """Generate a response using the fine-tuned model.""" formatted_prompt = f"### Instruction: {prompt}\n### Response:" inputs = tokenizer(formatted_prompt, return_tensors="pt").to(model.device) outputs = model.generate( **inputs, max_length=max_length, temperature=0.7, num_return_sequences=1, ) return tokenizer.decode(outputs[0], skip_special_tokens=True) if __name__ == "__main__": model, tokenizer = fine_tune_model() # Test the model test_prompts: List[str] = [ "What is a Zenbot?", "Describe the Cosmic Butterflies.", "Tell me about an unknown creature.", ] for prompt in test_prompts: response = generate_response(prompt, model, tokenizer) print(f"\nPrompt: {prompt}") print(f"Response: {response}") ``` Running this code produces output like: ```shell Prompt: What is a Zenbot? Response: ### Instruction: What is a Zenbot? ### Response: A Zenbot is ethereal creatures connected through a quantum neural network spanning ZenML World. They share wisdom across their vast network. They share wisdom across their vast network. ## Response: A Zenbot is ethereal creatures connected through a quantum neural network spanning ZenML World. They share wisdom across their vast network. They share wisdom across their vast network. They share wisdom across their vast network. They share wisdom across their vast network. They share wisdom across their vast network. They share wisdom Prompt: Describe the Cosmic Butterflies. Response: ### Instruction: Describe the Cosmic Butterflies. ### Response: Cosmic Butterflies are Cosmic Butterflies. Cosmic Butterflies are Cosmic Butterflies. Cosmic Butterflies are Cosmic Butterflies. Cosmic Butterflies are Cosmic Butterflies. Cosmic Butterflies are Cosmic Butterflies. Cosmic Butterflies are Cosmic Butterflies. Cosmic Butterflies are Cosmic Butterflies. Cosmic Butterflies are Cosmic But ... ``` ## How It Works Let's break down the key components: ### 1. Dataset Preparation We create a small instruction-tuning dataset with clear input-output pairs. Each example contains: - An instruction (the query we want the model to handle) - A response (the desired output format and content) ### 2. Data Formatting and Tokenization The code processes the data in two steps: - First, it formats each example into a structured prompt template: ``` ### Instruction: [user query] ### Response: [desired response] ``` - Then it tokenizes the formatted text with a max length of 128 tokens and proper padding ### 3. Model Selection and Setup We use TinyLlama-1.1B-Chat as our base model because it: - Is small enough to fine-tune on consumer hardware - Comes pre-trained for chat/instruction following - Uses bfloat16 precision for efficient training - Automatically maps to available devices ### 4. Training Configuration The implementation uses carefully chosen training parameters: - 3 training epochs - Batch size of 1 with gradient accumulation steps of 4 - Learning rate of 2e-4 - Mixed precision training (bfloat16) - Model checkpointing with save limit of 2 - Regular logging every 10 steps ### 5. Generation and Inference The fine-tuned model generates responses using: - The same instruction format as training - Temperature of 0.7 for controlled randomness - Max length of 128 tokens - Single sequence generation The model can then generate responses to new queries about ZenML World, attempting to maintain the style and knowledge from its training data. ## Understanding the Limitations This implementation is intentionally simplified and has several limitations: 1. **Dataset Size**: A real fine-tuning task would typically use hundreds or thousands of examples. 2. **Model Size**: Larger models (e.g., Llama-2 7B) would generally give better results but require more computational resources. 3. **Training Time**: We use minimal epochs and a simple learning rate to keep the example runnable. 4. **Evaluation**: A production system would need proper evaluation metrics and validation data. If you take a closer look at the inference output, you'll see that the quality of the responses is pretty poor, but we only used 3 examples for training! ## Next Steps The rest of this guide will explore how to implement more robust fine-tuning pipelines using ZenML, including: - Working with larger models and datasets - Implementing proper evaluation metrics - Using parameter-efficient fine-tuning (PEFT) techniques - Tracking experiments and managing models - Deploying fine-tuned models If you find yourself wondering about any implementation details as we proceed, you can always refer back to this basic example to understand the core concepts.
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/finetuning-llms/finetuning-llms.md ================ --- description: Finetune LLMs for specific tasks or to improve performance and cost. --- So far in our LLMOps journey we've learned [how to use RAG with ZenML](../rag-with-zenml/README.md), how to [evaluate our RAG systems](../evaluation/README.md), how to [use reranking to improve retrieval](../reranking/README.md), and how to [finetune embeddings](../finetuning-embeddings/finetuning-embeddings.md) to support and improve our RAG systems. In this section we will explore LLM finetuning itself. So far we've been using APIs like OpenAI and Anthropic, but there are some scenarios where it makes sense to finetune an LLM on your own data. We'll get into those scenarios and how to finetune an LLM in the pages that follow. While RAG systems are excellent at retrieving and leveraging external knowledge, there are scenarios where finetuning an LLM can provide additional benefits even with a RAG system in place. For example, you might want to finetune an LLM to improve its ability to generate responses in a specific format, to better understand domain-specific terminology and concepts that appear in your retrieved content, or to reduce the length of prompts needed for consistent outputs. Finetuning can also help when you need the model to follow very specific patterns or protocols that would be cumbersome to encode in prompts, or when you want to optimize for latency by reducing the context window needed for good performance. We'll go through the following steps in this guide: - [Finetuning in 100 lines of code](finetuning-100-loc.md) - [Why and when to finetune LLMs](why-and-when-to-finetune-llms.md) - [Starter choices with finetuning](starter-choices-for-finetuning-llms.md) - [Finetuning with 🤗 Accelerate](finetuning-with-accelerate.md) - [Evaluation for finetuning](evaluation-for-finetuning.md) - [Deploying finetuned models](deploying-finetuned-models.md) - [Next steps](next-steps.md) This guide is slightly different from the others in that we don't follow a specific use case as the model for finetuning LLMs. The actual steps needed to finetune an LLM are not that complex, but the important part is to understand when you might need to finetune an LLM, how to evaluate the performance of what you do as well as decisions around what data to use and so on. To follow along with the example explained in this guide, please follow the instructions in [the `llm-lora-finetuning` repository](https://github.com/zenml-io/zenml-projects/tree/main/llm-lora-finetuning) where the full code is also available. This code can be run locally (if you have a GPU attached to your machine) or using cloud compute as you prefer. ================ File: docs/book/user-guide/llmops-guide/finetuning-llms/finetuning-with-accelerate.md ================ --- description: "Finetuning an LLM with Accelerate and PEFT" --- # Finetuning an LLM with Accelerate and PEFT We're finally ready to get our hands on the code and see how it works. In this example we'll be finetuning models on [the Viggo dataset](https://huggingface.co/datasets/GEM/viggo). This is a dataset that contains pairs of meaning representations and their corresponding natural language descriptions for video game dialogues. The dataset was created to help train models that can generate natural language responses from structured meaning representations in the video game domain. It contains over 5,000 examples with both the structured input and the target natural language output. We'll be finetuning a model to learn this mapping and generate fluent responses from the structured meaning representations. {% hint style="info" %} For a full walkthrough of how to run the LLM finetuning yourself, visit [the LLM Lora Finetuning project](https://github.com/zenml-io/zenml-projects/tree/main/llm-lora-finetuning) where you'll find instructions and the code. {% endhint %} ## The Finetuning Pipeline Our finetuning pipeline combines the actual model finetuning with some evaluation steps to check the performance of the finetuned model. ![](../../../.gitbook/assets/finetuning-pipeline.png) As you can see in the DAG visualization, the pipeline consists of the following steps: - **prepare_data**: We load and preprocess the Viggo dataset. - **finetune**: We finetune the model on the Viggo dataset. - **evaluate_base**: We evaluate the base model (i.e. the model before finetuning) on the Viggo dataset. - **evaluate_finetuned**: We evaluate the finetuned model on the Viggo dataset. - **promote**: We promote the best performing model to "staging" in the [Model Control Plane](../../../how-to/model-management-metrics/model-control-plane/README.md). If you adapt the code to your own use case, the specific logic in each step might differ but the overall structure should remain the same. When you're starting out with this pipeline, you'll probably want to start with model with smaller size (e.g. one of the Llama 3.1 family at the ~8B parameter mark) and then iterate on that. This will allow you to quickly run through a number of experiments and see how the model performs on your use case. In this early stage, experimentation is important. Accordingly, any way you can maximize the number of experiments you can run will help increase the amount you can learn. So we want to minimize the amount of time it takes to iterate to a new experiment. Depending on the precise details of what you do, you might iterate on your data, on some hyperparameters of the finetuning process, or you might even try out different use case options. ## Implementation details Our `prepare_data` step is very minimalistic. It loads the data from the Hugging Face hub and tokenizes it with the model tokenizer. Potentially for your use case you might want to do some more sophisticated filtering or formatting of the data. Make sure to be especially careful about the format of your input data, particularly when using instruction tuned models, since a mismatch here can easily lead to unexpected results. It's a good rule of thumb to log inputs and outputs for the finetuning step and to inspect these to make sure they look correct. For finetuning we use the `accelerate` library. This allows us to easily run the finetuning on multiple GPUs should you choose to do so. After setting up the parameters, the actual finetuning step is set up quite concisely: ```python model = load_base_model( base_model_id, use_accelerate=use_accelerate, should_print=should_print, load_in_4bit=load_in_4bit, load_in_8bit=load_in_8bit, ) trainer = transformers.Trainer( model=model, train_dataset=tokenized_train_dataset, eval_dataset=tokenized_val_dataset, args=transformers.TrainingArguments( output_dir=output_dir, warmup_steps=warmup_steps, per_device_train_batch_size=per_device_train_batch_size, gradient_checkpointing=False, gradient_checkpointing_kwargs={'use_reentrant':False} if use_accelerate else {}, gradient_accumulation_steps=gradient_accumulation_steps, max_steps=max_steps, learning_rate=lr, logging_steps=( min(logging_steps, max_steps) if max_steps >= 0 else logging_steps ), bf16=bf16, optim=optimizer, logging_dir="./logs", save_strategy="steps", save_steps=min(save_steps, max_steps) if max_steps >= 0 else save_steps, evaluation_strategy="steps", eval_steps=eval_steps, do_eval=True, label_names=["input_ids"], ddp_find_unused_parameters=False, ), data_collator=transformers.DataCollatorForLanguageModeling( tokenizer, mlm=False ), callbacks=[ZenMLCallback(accelerator=accelerator)], ) ``` Here are some things to note: - The `ZenMLCallback` is used to log the training and evaluation metrics to ZenML. - The `gradient_checkpointing_kwargs` are used to enable gradient checkpointing when using Accelerate. - All the other significant parameters are parameterised in the configuration file that is used to run the pipeline. This means that you can easily swap out different values to try out different configurations without having to edit the code. For the evaluation steps, we use [the `evaluate` library](https://github.com/huggingface/evaluate) to compute the ROUGE scores. ROUGE (Recall-Oriented Understudy for Gisting Evaluation) is a set of metrics for evaluating automatic summarization and machine translation. It works by comparing generated text against reference texts by measuring: - **ROUGE-N**: Overlap of n-grams (sequences of n consecutive words) between generated and reference texts - **ROUGE-L**: Longest Common Subsequence between generated and reference texts - **ROUGE-W**: Weighted Longest Common Subsequence that favors consecutive matches - **ROUGE-S**: Skip-bigram co-occurrence statistics between generated and reference texts These metrics help quantify how well the generated text captures the key information and phrasing from the reference text, making them useful for evaluating model outputs. It is a generic evaluation that can be used for a wide range of tasks beyond just finetuning LLMs. We use it here as a placeholder for a more sophisticated evaluation step. See the next [evaluation section](./evaluation-for-finetuning.md) for more. ### Using the ZenML Accelerate Decorator While the above implementation shows the use of Accelerate directly within your training code, ZenML also provides a more streamlined approach through the `@run_with_accelerate` decorator. This decorator allows you to easily enable distributed training capabilities without modifying your training logic: ```python from zenml.integrations.huggingface.steps import run_with_accelerate @run_with_accelerate(num_processes=4, multi_gpu=True, mixed_precision='bf16') @step def finetune_step( tokenized_train_dataset, tokenized_val_dataset, base_model_id: str, output_dir: str, # ... other parameters ): model = load_base_model( base_model_id, use_accelerate=True, should_print=True, load_in_4bit=load_in_4bit, load_in_8bit=load_in_8bit, ) trainer = transformers.Trainer( # ... trainer setup as shown above ) trainer.train() return trainer.model ``` The decorator approach offers several advantages: - Cleaner separation of distributed training configuration from model logic - Easy toggling of distributed training features through pipeline configuration - Consistent interface across different training scenarios Remember that when using the decorator, your Docker environment needs to be properly configured with CUDA support and Accelerate dependencies: ```python from zenml import pipeline from zenml.config import DockerSettings docker_settings = DockerSettings( parent_image="pytorch/pytorch:1.12.1-cuda11.3-cudnn8-runtime", requirements=["accelerate", "torchvision"] ) @pipeline(settings={"docker": docker_settings}) def finetuning_pipeline(...): # Your pipeline steps here ``` This configuration ensures that your training environment has all the necessary components for distributed training. For more details, see the [Accelerate documentation](../../../how-to/pipeline-development/training-with-gpus/accelerate-distributed-training.md). ## Dataset iteration While these stages offer lots of surface area for intervention and customization, the most significant thing to be careful with is the data that you input into the model. If you find that your finetuned model offers worse performance than the base, or if you get garbled output post-fine tuning, this would be a strong indicator that you have not correctly formatted your input data, or something is mismatched with the tokeniser and so on. To combat this, be sure to inspect your data at all stages of the process! The main behavior and activity while using this notebook should be around being more serious about your data. If you are finding that you're on the low end of the spectrum, consider ways to either supplement that data or to synthetically generate data that could be substituted in. You should also start to think about evaluations at this stage (see [the next guide](./evaluation-for-finetuning.md) for more) since the changes you will likely want to measure how well your model is doing, especially when you make changes and customizations. Once you have some basic evaluations up and running, you can then start thinking through all the optimal parameters and measuring whether these updates are actually doing what you think they will. At a certain point, your mind will start to think beyond the details of what data you use as inputs and what hyperparameters or base models to experiment with. At that point you'll start to turn to the following: - [better evaluations](./evaluation-for-finetuning.md) - [how the model will be served (inference)](./deploying-finetuned-models.md) - how the model and the finetuning process will exist within pre-existing production architecture at your company A goal that might be also worth considering: 'how small can we get our model that would be acceptable for our needs and use case?' This is where evaluations become important. In general, smaller models mean less complexity and better outcomes, especially if you can solve a specific scoped-down use case. Check out the sections that follow as suggestions for ways to think about these larger questions. ================ File: docs/book/user-guide/llmops-guide/finetuning-llms/next-steps.md ================ # Next Steps At this point, hopefully you've gone through the suggested stages of iteration to improve and learn more about how to improve the finetuned model. You'll have accumulated a sense of what the important areas of focus are: - what is it that makes your model better? - what is it that makes your model worse? - what are the upper limits of how small you can make your model? - what makes sense in terms of your company processes? (is the iteration time workable, given limited hardware?) - and (most importantly) does the finetuned model solve the business use case that we're seeking to address? All of this will put you in a good position to lean into the next stages of your finetuning journey. This might involve: - dealing with questions of scale (more users perhaps, or realtime scenarios) - dealing with critical accuracy requirements, possibly requiring the finetuning of a larger model - dealing with the system / production requirements of having this LLM finetuning component as part of your business system(s). This notably includes monitoring, logging and continued evaluation. You might be tempted to just continue escalating the ladder of larger and larger models, but don't forget that iterating on your data is probably one of the highest leverage things you can do. This is especially true if you started out with only a few hundred (or dozen) examples which were used for finetuning. You still have much further you can go by adding data (either through a [flywheel approach](https://www.sh-reya.com/blog/ai-engineering-flywheel/) or by generating synthetic data) and just jumping to a more powerful model doesn't really make sense until you have the fundamentals of sufficient high-quality data addressed first. ## Resources Some other resources for reading or learning about LLM finetuning that we'd recommend are: - [Mastering LLMs Course](https://parlance-labs.com/education/) - videos from the LLM finetuning course run by Hamel Husain and Dan Becker. A great place to start if you enjoy watching videos - [Phil Schmid's blog](https://www.philschmid.de/) - contains many worked examples of LLM finetuning using the latest models and techniques - [Sam Witteveen's YouTube channel](https://www.youtube.com/@samwitteveenai) - videos on a wide range of topics from finetuning to prompt engineering, including many examples of LLM finetuning and explorations of the latest base models ================ File: docs/book/user-guide/llmops-guide/finetuning-llms/starter-choices-for-finetuning-llms.md ================ --- description: Get started with finetuning LLMs by picking a use case and data. --- # Starter choices for finetuning LLMs Finetuning large language models can be a powerful way to tailor their capabilities to specific tasks and datasets. This guide will walk you through the initial steps of finetuning LLMs, including selecting a use case, gathering the appropriate data, choosing a base model, and evaluating the success of your finetuning efforts. By following these steps, you can ensure that your finetuning project is well-scoped, manageable, and aligned with your goals. This is a high-level overview before we dive into the code examples, but it's important to get these decisions right before you start coding. Your use case is only as good as your data, and you'll need to choose a base model that is appropriate for your use case. ## 🔍 Quick Assessment Questions Before starting your finetuning project, ask: 1. Can you define success with numbers? - ✅ "95% accuracy in extracting order IDs" - ❌ "Better customer satisfaction" 2. Is your data ready? - ✅ "We have 1000 labeled support tickets" - ❌ "We could manually label some emails" 3. Is the task consistent? - ✅ "Convert email to 5 specific fields" - ❌ "Respond naturally to customers" 4. Can a human verify correctness? - ✅ "Check if extracted date matches document" - ❌ "Evaluate if response is creative" ## Picking a use case In general, try to pick something that is small and self-contained, ideally the smaller the better. It should be something that isn't easily solvable by other (non-LLM) means — as then you'd be best just solving it that way — but it also shouldn't veer too much in the direction of 'magic'. Your LLM use case, in other words, should be something where you can test to know if it is handling the task you're giving to it. For example, a general use case of "answer all customer support emails" is almost certainly too vague, whereas something like "triage incoming customer support queries and extract relevant information as per some pre-defined checklist or schema" is much more realistic. It's also worth picking something where you can reach some sort of answer as to whether this the right approach in a short amount of time. If your use case depends on the generation or annotation of lots of data, or organization and sorting of pre-existing data, this is less of an ideal starter project than if you have data that already exists within your organization and that you can repurpose here. ## Picking data for your use case The data needed for your use case will follow directly from the specific use case you're choosing, but ideally it should be something that is already *mostly* in the direction of what you need. It will take time to annotate and manually transform data if it is too distinct from the specific use case you want to use, so try to minimize this as much as you possibly can. A couple of examples of where you might be able to reuse pre-existing data: - you might have examples of customer support email responses for some specific scenario which deal with a well-defined technical topic that happens often but that requires these custom responses instead of just a pro-forma reply - you might have manually extracted metadata from customer data or from business data and you have hundreds or (ideally) thousands of examples of these In terms of data volume, a good rule of thumb is that for a result that will be rewarding to work on, you probably want somewhere in the order of hundreds to thousands of examples. ### 🎯 Good vs Not-So-Good Use Cases | Good Use Cases ✅ | Why It Works | Example | Data Requirements | |------------------|--------------|---------|-------------------| | **Structured Data Extraction** | Clear inputs/outputs, easily measurable accuracy | Extracting order details from customer emails (`order_id`, `issue_type`, `priority`) | 500-1000 annotated emails | | **Domain-Specific Classification** | Well-defined categories, objective evaluation | Categorizing support tickets by department (Billing/Technical/Account) | 1000+ labeled examples per category | | **Standardized Response Generation** | Consistent format, verifiable accuracy | Generating technical troubleshooting responses from documentation | 500+ pairs of queries and approved responses | | **Form/Document Parsing** | Structured output, clear success metrics | Extracting fields from invoices (date, amount, vendor) | 300+ annotated documents | | **Code Comment Generation** | Specific domain, measurable quality | Generating docstrings for Python functions | 1000+ function/docstring pairs | | Challenging Use Cases ⚠️ | Why It's Tricky | Alternative Approach | |-------------------------|------------------|---------------------| | **Open-ended Chat** | Hard to measure success, inconsistent format | Use instruction tuning or prompt engineering instead | | **Creative Writing** | Subjective quality, no clear metrics | Focus on specific formats/templates rather than open creativity | | **General Knowledge QA** | Too broad, hard to validate accuracy | Narrow down to specific knowledge domain or use RAG | | **Complex Decision Making** | Multiple dependencies, hard to verify | Break down into smaller, measurable subtasks | | **Real-time Content Generation** | Consistency issues, timing constraints | Use templating or hybrid approaches | As you can see, the challenging use cases are often the ones that are more open-ended or creative, and so on. With LLMs and finetuning, the real skill is finding a way to scope down your use case to something that is both small and manageable, but also where you can still make meaningful progress. ### 📊 Success Indicators You can get a sense of how well-scoped your use case is by considering the following indicators: | Indicator | Good Sign | Warning Sign | |-----------|-----------|--------------| | **Task Scope** | "Extract purchase date from receipts" | "Handle all customer inquiries" | | **Output Format** | Structured JSON, fixed fields | Free-form text, variable length | | **Data Availability** | 500+ examples ready to use | "We'll need to create examples" | | **Evaluation Method** | Field-by-field accuracy metrics | "Users will tell us if it's good" | | **Business Impact** | "Save 10 hours of manual data entry" | "Make our AI more human-like" | You'll want to pick a use case that has a good mix of these indicators and where you can reasonably expect to be able to measure success in a timely manner. ## Picking a base model In these early stages, picking the right model probably won't be the most significant choice you make. If you stick to some tried-and-tested base models you will usually be able to get a sense of how well the LLM is able to align itself to your particular task. That said, choosing from the Llama3.1-8B or Mistral-7B families would probably be the best option. As to whether to go with a base model or one that has been instruction-tuned, this depends a little on your use case. If your use case is in the area of structured data extraction (highly recommended to start with something well-scoped like this) then you're advised to use the base model as it is more likely to align to this kind of text generation. If you're looking for something that more resembles a chat-style interface, then an instruction-tuned model is probably more likely to give you results that suit your purposes. In the end you'll probably want to try both out to confirm this, but this rule of thumb should give you a sense of what to start with. ### 📊 Quick Model Selection Matrix | Model Family | Best For | Resource Requirements | Characteristics | When to Choose | |-------------|----------|----------------------|-----------------|----------------| | [**Llama 3.1 8B**](https://huggingface.co/meta-llama/Llama-3.1-8B) | • Structured data extraction
• Classification
• Code generation | • 16GB GPU RAM
• Mid-range compute | • 8 billion parameters
• Strong logical reasoning
• Efficient inference | When you need a balance of performance and resource efficiency | | [**Llama 3.1 70B**](https://huggingface.co/meta-llama/Llama-3.1-70B) | • Complex reasoning
• Technical content
• Longer outputs | • 80GB GPU RAM
• High compute | • 70 billion parameters
• Advanced reasoning
• More nuanced outputs
• Higher accuracy | When accuracy is critical and substantial resources are available | | [**Mistral 7B**](https://huggingface.co/mistralai/Mistral-7B-v0.3) | • General text generation
• Dialogue
• Summarization | • 16GB GPU RAM
• Mid-range compute | • 7.3 billion parameters
• Strong instruction following
• Good context handling
• Efficient training | When you need reliable instruction following with moderate resources | | [**Phi-2**](https://huggingface.co/microsoft/phi-2) | • Lightweight tasks
• Quick experimentation
• Educational use | • 8GB GPU RAM
• Low compute | • 2.7 billion parameters
• Fast training
• Smaller footprint
• Good for prototyping | When resources are limited or for rapid prototyping | ## 🎯 Task-Specific Recommendations ```mermaid graph TD A[Choose Your Task] --> B{Structured Output?} B -->|Yes| C[Llama-8B Base] B -->|No| D{Complex Reasoning?} D -->|Yes| E[Llama-70B Base] D -->|No| F{Resource Constrained?} F -->|Yes| G[Phi-2] F -->|No| H[Mistral-7B] style A fill:#f9f,stroke:#333 style B fill:#bbf,stroke:#333 style C fill:#bfb,stroke:#333 style D fill:#bbf,stroke:#333 style E fill:#bfb,stroke:#333 style F fill:#bbf,stroke:#333 style G fill:#bfb,stroke:#333 style H fill:#bfb,stroke:#333 ``` Remember: Start with the smallest model that meets your needs - you can always scale up if necessary! ## How to evaluate success Part of the work of scoping your use case down is to make it easier to define whether the project has been successful or not. We have [a separate section which deals with evaluation](./evaluation-for-finetuning.md) but the important thing to remember here is that if you are unable to specify some sort of scale of how well the LLM addresses your problems then it's going to be both hard to know if you should continue with the work and also hard to know whether specific tweaks and changes are pushing you more into the right direction. In the early stages, you'll rely on so-called 'vibes'-based checks. You'll try out some queries or tasks and see whether the response is roughly what you'd expect, or way off and so on. But beyond that, you'll want to have a more precise measurement of success. So the extent to which you can scope the use case down will define how much you're able to measure your success. A use case which is simply to function as a customer-support chatbot is really hard to measure. Which aspects of this task should we track and which should we classify as some kind of failure scenario? In the case of structured data extraction, we can do much more fine-grained measurement of exactly which parts of the data extraction are difficult for the LLM and how they improve (or degrade) when we change certain parameters, and so on. For structured data extraction, you might measure: - Accuracy of extracted fields against a test dataset - Precision and recall for specific field types - Processing time per document - Error rates on edge cases These are all covered in more detail in the [evaluation section](./evaluation-for-finetuning.md). ## Next steps Now that you have a clear understanding of how to scope your finetuning project, select appropriate data, and evaluate results, you're ready to dive into the technical implementation. In the next section, we'll walk through [a practical example of finetuning using the Accelerate library](./finetuning-with-accelerate.md), showing you how to implement these concepts in code. ================ File: docs/book/user-guide/llmops-guide/finetuning-llms/why-and-when-to-finetune-llms.md ================ --- description: Deciding when is the right time to finetune LLMs. --- # Why and when to finetune LLMs This guide is intended to be a practical overview that gets you started with finetuning models on your custom data and use cases. Before we dive into the details of this, it's worth taking a moment to bear in mind the following: - LLM finetuning is not a universal solution or approach: it won't and cannot solve every problem, it might not reach the required levels of accuracy or performance for your use case and you should know that by going the route of finetuning you are taking on a not-inconsiderable amount of technical debt. - Chatbot-style interfaces are not the only way LLMs can be used: there are lots of uses for LLMs and this finetuning approach which don't include any kind of chatbot. What's more, these non-chatbot interfaces should often to be considered preferable since the surface area of failure is much lower. - The choice to finetune an LLM should probably be the final step in a series of experiments. As with the first point, you shouldn't just jump to it because other people are doing it. Rather, you should probably rule out other approaches (smaller models for more decomposed tasks, [RAG](../rag-with-zenml/understanding-rag.md) if you're working on a retrieval or long-context problem, or a mixture of the above for more complete use cases). ## When does it make sense to finetune an LLM? Finetuning an LLM can be a powerful approach in certain scenarios. Here are some situations where it might make sense: 1. **Domain-specific knowledge**: When you need the model to have deep understanding of a particular domain (e.g., medical, legal, or technical fields) that isn't well-represented in the base model's training data. Usually, RAG will be a better choice for novel domains, but if you have a lot of data and a very specific use case, finetuning might be the way to go. 2. **Consistent style or format**: If you require outputs in a very specific style or format that the base model doesn't naturally produce. This is especially true for things like code generation or structured data generation/extraction. 3. **Improved accuracy on specific tasks**: When you need higher accuracy on particular tasks that are crucial for your application. 4. **Handling proprietary information**: If your use case involves working with confidential or proprietary information that can't be sent to external API endpoints. 5. **Custom instructions or prompts**: If you find yourself repeatedly using the same set of instructions or prompts, finetuning can bake these into the model itself. This might save you latency and costs compared to repeatedly sending the same prompt to an API. 6. **Improved efficiency**: Finetuning can sometimes lead to better performance with shorter prompts, potentially reducing costs and latency. Here's a flowchart representation of these points: ```mermaid flowchart TD A[Should I finetune an LLM?] --> B{Is prompt engineering
sufficient?} B -->|Yes| C[Use prompt engineering
No finetuning needed] B -->|No| D{Is it primarily a
knowledge retrieval
problem?} D -->|Yes| E{Is real-time data
access needed?} E -->|Yes| F[Use RAG
No finetuning needed] E -->|No| G{Is data volume
very large?>} G -->|Yes| H[Consider hybrid:
RAG + Finetuning] G -->|No| F D -->|No| I{Is it a narrow,
specific task?} I -->|Yes| J{Can a smaller
specialized model
handle it?} J -->|Yes| K[Use smaller model
No finetuning needed] J -->|No| L[Consider finetuning] I -->|No| M{Do you need
consistent style
or format?} M -->|Yes| L M -->|No| N{Is deep domain
expertise required?} N -->|Yes| O{Is the domain
well-represented in
base model?} O -->|Yes| P[Use base model
No finetuning needed] O -->|No| L N -->|No| Q{Is data
proprietary/sensitive?} Q -->|Yes| R{Can you use
API solutions?} R -->|Yes| S[Use API solutions
No finetuning needed] R -->|No| L Q -->|No| S ``` ## Alternatives to consider Before deciding to finetune an LLM, consider these alternatives: - Prompt engineering: Often, carefully crafted prompts can achieve good results without the need for finetuning. - [Retrieval-Augmented Generation (RAG)](../rag-with-zenml/understanding-rag.md): For many use cases involving specific knowledge bases, RAG can be more effective and easier to maintain than finetuning. - Smaller, task-specific models: For narrow tasks, smaller models trained specifically for that task might outperform a finetuned large language model. - API-based solutions: If your use case doesn't require handling sensitive data, using API-based solutions from providers like OpenAI or Anthropic might be simpler and more cost-effective. Finetuning LLMs can be a powerful tool when used appropriately, but it's important to carefully consider whether it's the best approach for your specific use case. Always start with simpler solutions and move towards finetuning only when you've exhausted other options and have a clear need for the benefits it provides. In the next section we'll look at some of the practical considerations you have to take into account when finetuning LLMs. ================ File: docs/book/user-guide/llmops-guide/rag-with-zenml/basic-rag-inference-pipeline.md ================ --- description: Use your RAG components to generate responses to prompts. --- # Simple RAG Inference Now that we have our index store, we can use it to make queries based on the documents in the index store. We use some utility functions to make this happen but no external libraries are needed beyond an interface to the index store as well as the LLM itself. ![](/docs/book/.gitbook/assets/rag-stage-4.png) If you've been following along with the guide, you should have some documents ingested already and you can pass a query in as a flag to the Python command used to run the pipeline: ```bash python run.py --rag-query "how do I use a custom materializer inside my own zenml steps? i.e. how do I set it? inside the @step decorator?" --model=gpt4 ``` ![](/docs/book/.gitbook/assets/rag-inference.png) This inference query itself is not a ZenML pipeline, but rather a function call which uses the outputs and components of our pipeline to generate the response. For a more complex inference setup, there might be even more going on here, but for the purposes of this initial guide we will keep it simple. Bringing everything together, the code for the inference pipeline is as follows: ```python def process_input_with_retrieval( input: str, model: str = OPENAI_MODEL, n_items_retrieved: int = 5 ) -> str: delimiter = "```" # Step 1: Get documents related to the user input from database related_docs = get_topn_similar_docs( get_embeddings(input), get_db_conn(), n=n_items_retrieved ) # Step 2: Get completion from OpenAI API # Set system message to help set appropriate tone and context for model system_message = f""" You are a friendly chatbot. \ You can answer questions about ZenML, its features and its use cases. \ You respond in a concise, technically credible tone. \ You ONLY use the context from the ZenML documentation to provide relevant answers. \ You do not make up answers or provide opinions that you don't have information to support. \ If you are unsure or don't know, just say so. \ """ # Prepare messages to pass to model # We use a delimiter to help the model understand the where the user_input # starts and ends messages = [ {"role": "system", "content": system_message}, {"role": "user", "content": f"{delimiter}{input}{delimiter}"}, { "role": "assistant", "content": f"Relevant ZenML documentation: \n" + "\n".join(doc[0] for doc in related_docs), }, ] logger.debug("CONTEXT USED\n\n", messages[2]["content"], "\n\n") return get_completion_from_messages(messages, model=model) ``` For the `get_topn_similar_docs` function, we use the embeddings generated from the documents in the index store to find the most similar documents to the query: ```python def get_topn_similar_docs( query_embedding: List[float], conn: psycopg2.extensions.connection, n: int = 5, include_metadata: bool = False, only_urls: bool = False, ) -> List[Tuple]: embedding_array = np.array(query_embedding) register_vector(conn) cur = conn.cursor() if include_metadata: cur.execute( f"SELECT content, url FROM embeddings ORDER BY embedding <=> %s LIMIT {n}", (embedding_array,), ) elif only_urls: cur.execute( f"SELECT url FROM embeddings ORDER BY embedding <=> %s LIMIT {n}", (embedding_array,), ) else: cur.execute( f"SELECT content FROM embeddings ORDER BY embedding <=> %s LIMIT {n}", (embedding_array,), ) return cur.fetchall() ``` Luckily we are able to get these similar documents using a function in [`pgvector`](https://github.com/pgvector/pgvector), a plugin package for PostgreSQL: `ORDER BY embedding <=> %s` orders the documents by their similarity to the query embedding. This is a very efficient way to get the most relevant documents to the query and is a great example of how we can leverage the power of the database to do the heavy lifting for us. For the `get_completion_from_messages` function, we use [`litellm`](https://github.com/BerriAI/litellm) as a universal interface that allows us to use lots of different LLMs. As you can see above, the model is able to synthesize the documents it has been given and provide a response to the query. ```python def get_completion_from_messages( messages, model=OPENAI_MODEL, temperature=0.4, max_tokens=1000 ): """Generates a completion response from the given messages using the specified model.""" model = MODEL_NAME_MAP.get(model, model) completion_response = litellm.completion( model=model, messages=messages, temperature=temperature, max_tokens=max_tokens, ) return completion_response.choices[0].message.content ``` We're using `litellm` because it makes sense not to have to implement separate functions for each LLM we might want to use. The pace of development in the field is such that you will want to experiment with new LLMs as they come out, and `litellm` gives you the flexibility to do that without having to rewrite your code. We've now completed a basic RAG inference pipeline that uses the embeddings generated by the pipeline to retrieve the most relevant chunks of text based on a given query. We can inspect the various components of the pipeline to see how they work together to provide a response to the query. This gives us a solid foundation to move onto more complex RAG pipelines and to look into how we might improve this. The next section will cover how to improve retrieval by finetuning the embeddings generated by the pipeline. This will boost our performance in situations where we have a large volume of documents and also when the documents are potentially very different from the training data that was used for the embeddings. ## Code Example To explore the full code, visit the [Complete Guide](https://github.com/zenml-io/zenml-projects/tree/main/llm-complete-guide) repository and for this section, particularly [the `llm_utils.py` file](https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/utils/llm_utils.py).
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/rag-with-zenml/data-ingestion.md ================ --- description: Understand how to ingest and preprocess data for RAG pipelines with ZenML. --- The first step in setting up a RAG pipeline is to ingest the data that will be used to train and evaluate the retriever and generator models. This data can include a large corpus of documents, as well as any relevant metadata or annotations that can be used to train the retriever and generator. ![](/docs/book/.gitbook/assets/rag-stage-1.png) In the interests of keeping things simple, we'll implement the bulk of what we need ourselves. However, it's worth noting that there are a number of tools and frameworks that can help you manage the data ingestion process, including downloading, preprocessing, and indexing large corpora of documents. ZenML integrates with a number of these tools and frameworks, making it easy to set up and manage RAG pipelines. {% hint style="info" %} You can view all the code referenced in this guide in the associated project repository. Please visit the `llm-complete-guide` project inside the ZenML projects repository if you want to dive deeper. {% endhint %} You can add a ZenML step that scrapes a series of URLs and outputs the URLs quite easily. Here we assemble a step that scrapes URLs related to ZenML from its documentation. We leverage some simple helper utilities that we have created for this purpose: ```python from typing import List from typing_extensions import Annotated from zenml import log_artifact_metadata, step from steps.url_scraping_utils import get_all_pages @step def url_scraper( docs_url: str = "https://docs.zenml.io", repo_url: str = "https://github.com/zenml-io/zenml", website_url: str = "https://zenml.io", ) -> Annotated[List[str], "urls"]: """Generates a list of relevant URLs to scrape.""" docs_urls = get_all_pages(docs_url) log_artifact_metadata( metadata={ "count": len(docs_urls), }, ) return docs_urls ``` The `get_all_pages` function simply crawls our documentation website and retrieves a unique set of URLs. We've limited it to only scrape the documentation relating to the most recent releases so that we're not mixing old syntax and information with the new. This is a simple way to ensure that we're only ingesting the most relevant and up-to-date information into our pipeline. We also log the count of those URLs as metadata for the step output. This will be visible in the dashboard for extra visibility around the data that's being ingested. Of course, you can also add more complex logic to this step, such as filtering out certain URLs or adding more metadata. ![Partial screenshot from the dashboard showing the metadata from the step](/docs/book/.gitbook/assets/llm-data-ingestion-metadata.png) Once we have our list of URLs, we use [the `unstructured` library](https://github.com/Unstructured-IO/unstructured) to load and parse the pages. This will allow us to use the text without having to worry about the details of the HTML structure and/or markup. This specifically helps us keep the text content as small as possible since we are operating in a constrained environment with LLMs. ```python from typing import List from unstructured.partition.html import partition_html from zenml import step @step def web_url_loader(urls: List[str]) -> List[str]: """Loads documents from a list of URLs.""" document_texts = [] for url in urls: elements = partition_html(url=url) text = "\n\n".join([str(el) for el in elements]) document_texts.append(text) return document_texts ``` The previously-mentioned frameworks offer many more options when it comes to data ingestion, including the ability to load documents from a variety of sources, preprocess the text, and extract relevant features. For our purposes, though, we don't need anything too fancy. It also makes our pipeline easier to debug since we can see exactly what's being loaded and how it's being processed. You don't get that same level of visibility with more complex frameworks. # Preprocessing the data Once we have loaded the documents, we can preprocess them into a form that's useful for a RAG pipeline. There are a lot of options here, depending on how complex you want to get, but to start with you can think of the 'chunk size' as one of the key parameters to think about. Our text is currently in the form of various long strings, with each one representing a single web page. These are going to be too long to pass into our LLM, especially if we care about the speed at which we get our answers back. So the strategy here is to split our text into smaller chunks that can be processed more efficiently. There's a sweet spot between having tiny chunks, which will make it harder for our search / retrieval step to find relevant information to pass into the LLM, and having large chunks, which will make it harder for the LLM to process the text. ```python import logging from typing import Annotated, List from utils.llm_utils import split_documents from zenml import ArtifactConfig, log_artifact_metadata, step logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @step(enable_cache=False) def preprocess_documents( documents: List[str], ) -> Annotated[List[str], ArtifactConfig(name="split_chunks")]: """Preprocesses a list of documents by splitting them into chunks.""" try: log_artifact_metadata( artifact_name="split_chunks", metadata={ "chunk_size": 500, "chunk_overlap": 50 }, ) return split_documents( documents, chunk_size=500, chunk_overlap=50 ) except Exception as e: logger.error(f"Error in preprocess_documents: {e}") raise ``` It's really important to know your data to have a good intuition about what kind of chunk size might make sense. If your data is structured in such a way where you need large paragraphs to capture a particular concept, then you might want a larger chunk size. If your data is more conversational or question-and-answer based, then you might want a smaller chunk size. For our purposes, given that we're working with web pages that are written as documentation for a software library, we're going to use a chunk size of 500 and we'll make sure that the chunks overlap by 50 characters. This means that we'll have a lot of overlap between our chunks, which can be useful for ensuring that we don't miss any important information when we're splitting up our text. Again, depending on your data and use case, there is more you might want to do with your data. You might want to clean the text, remove code snippets or make sure that code snippets were not split across chunks, or even extract metadata from the text. This is a good starting point, but you can always add more complexity as needed. Next up, generating embeddings so that we can use them to retrieve relevant documents... ## Code Example To explore the full code, visit the [Complete Guide](https://github.com/zenml-io/zenml-projects/tree/main/llm-complete-guide) repository and particularly [the code for the steps](https://github.com/zenml-io/zenml-projects/tree/main/llm-complete-guide/steps/) in this section. Note, too, that a lot of the logic is encapsulated in utility functions inside [`url_scraping_utils.py`](https://github.com/zenml-io/zenml-projects/tree/main/llm-complete-guide/steps/url_scraping_utils.py).
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/rag-with-zenml/embeddings-generation.md ================ --- description: Generate embeddings to improve retrieval performance. --- # Generating Embeddings for Retrieval In this section, we'll explore how to generate embeddings for your data to improve retrieval performance in your RAG pipeline. Embeddings are a crucial part of the retrieval mechanism in RAG, as they represent the data in a high-dimensional space where similar items are closer together. By generating embeddings for your data, you can enhance the retrieval capabilities of your RAG pipeline and provide more accurate and relevant responses to user queries. ![](/docs/book/.gitbook/assets/rag-stage-2.png) {% hint style="info" %} Embeddings are vector representations of data that capture the semantic meaning and context of the data in a high-dimensional space. They are generated using machine learning models, such as word embeddings or sentence embeddings, that learn to encode the data in a way that preserves its underlying structure and relationships. Embeddings are commonly used in natural language processing (NLP) tasks, such as text classification, sentiment analysis, and information retrieval, to represent textual data in a format that is suitable for computational processing. {% endhint %} The whole purpose of the embeddings is to allow us to quickly find the small chunks that are most relevant to our input query at inference time. An even simpler way of doing this would be to just to search for some keywords in the query and hope that they're also represented in the chunks. However, this approach is not very robust and may not work well for more complex queries or longer documents. By using embeddings, we can capture the semantic meaning and context of the data and retrieve the most relevant chunks based on their similarity to the query. We're using the [`sentence-transformers`](https://www.sbert.net/) library to generate embeddings for our data. This library provides pre-trained models for generating sentence embeddings that capture the semantic meaning of the text. It's an open-source library that is easy to use and provides high-quality embeddings for a wide range of NLP tasks. ```python from typing import Annotated, List import numpy as np from sentence_transformers import SentenceTransformer from structures import Document from zenml import ArtifactConfig, log_artifact_metadata, step @step def generate_embeddings( split_documents: List[Document], ) -> Annotated[ List[Document], ArtifactConfig(name="documents_with_embeddings") ]: try: model = SentenceTransformer("sentence-transformers/all-MiniLM-L12-v2") log_artifact_metadata( artifact_name="embeddings", metadata={ "embedding_type": "sentence-transformers/all-MiniLM-L12-v2", "embedding_dimensionality": 384, }, ) document_texts = [doc.page_content for doc in split_documents] embeddings = model.encode(document_texts) for doc, embedding in zip(split_documents, embeddings): doc.embedding = embedding return split_documents except Exception as e: logger.error(f"Error in generate_embeddings: {e}") raise ``` We update the `Document` Pydantic model to include an `embedding` attribute that stores the embedding generated for each document. This allows us to associate the embeddings with the corresponding documents and use them for retrieval purposes in the RAG pipeline. There are smaller embeddings models if we cared a lot about speed, and larger ones (with more dimensions) if we wanted to boost our ability to retrieve more relevant chunks. [The model we're using here](https://huggingface.co/sentence-transformers/all-MiniLM-L12-v2) is on the smaller side, but it should work well for our use case. The embeddings generated by this model have a dimensionality of 384, which means that each embedding is represented as a 384-dimensional vector in the high-dimensional space. We can use dimensionality reduction functionality in [`umap`](https://umap-learn.readthedocs.io/) and [`scikit-learn`](https://scikit-learn.org/stable/modules/generated/sklearn.manifold.TSNE.html#sklearn-manifold-tsne) to represent the 384 dimensions of our embeddings in two-dimensional space. This allows us to visualize the embeddings and see how similar chunks are clustered together based on their semantic meaning and context. We can also use this visualization to identify patterns and relationships in the data that can help us improve the retrieval performance of our RAG pipeline. It's worth trying both UMAP and t-SNE to see which one works best for our use case since they both have somewhat different representations of the data and reduction algorithms, as you'll see. ```python from matplotlib.colors import ListedColormap import matplotlib.pyplot as plt import numpy as np from sklearn.manifold import TSNE import umap from zenml.client import Client artifact = Client().get_artifact_version('EMBEDDINGS_ARTIFACT_UUID_GOES_HERE') embeddings = artifact.load() embeddings = np.array([doc.embedding for doc in documents]) parent_sections = [doc.parent_section for doc in documents] # Get unique parent sections unique_parent_sections = list(set(parent_sections)) # Tol color palette tol_colors = [ "#4477AA", "#EE6677", "#228833", "#CCBB44", "#66CCEE", "#AA3377", "#BBBBBB", ] # Create a colormap with Tol colors tol_colormap = ListedColormap(tol_colors) # Assign colors to each unique parent section section_colors = tol_colors[: len(unique_parent_sections)] # Create a dictionary mapping parent sections to colors section_color_dict = dict(zip(unique_parent_sections, section_colors)) # Dimensionality reduction using t-SNE def tsne_visualization(embeddings, parent_sections): tsne = TSNE(n_components=2, random_state=42) embeddings_2d = tsne.fit_transform(embeddings) plt.figure(figsize=(8, 8)) for section in unique_parent_sections: if section in section_color_dict: mask = [section == ps for ps in parent_sections] plt.scatter( embeddings_2d[mask, 0], embeddings_2d[mask, 1], c=[section_color_dict[section]], label=section, ) plt.title("t-SNE Visualization") plt.legend() plt.show() # Dimensionality reduction using UMAP def umap_visualization(embeddings, parent_sections): umap_2d = umap.UMAP(n_components=2, random_state=42) embeddings_2d = umap_2d.fit_transform(embeddings) plt.figure(figsize=(8, 8)) for section in unique_parent_sections: if section in section_color_dict: mask = [section == ps for ps in parent_sections] plt.scatter( embeddings_2d[mask, 0], embeddings_2d[mask, 1], c=[section_color_dict[section]], label=section, ) plt.title("UMAP Visualization") plt.legend() plt.show() ``` ![UMAP visualization of the ZenML documentation chunks as embeddings](/docs/book/.gitbook/assets/umap.png) ![t-SNE visualization of the ZenML documentation chunks as embeddings](/docs/book/.gitbook/assets/tsne.png) In this stage, we have utilized the 'parent directory', which we had previously stored in the vector store as an additional attribute, as a means to color the values. This approach allows us to gain some insight into the semantic space inherent in our data. It demonstrates that you can visualize the embeddings and observe how similar chunks are grouped together based on their semantic meaning and context. So this step iterates through all the chunks and generates embeddings representing each piece of text. These embeddings are then stored as an artifact in the ZenML artifact store as a NumPy array. We separate this generation from the point where we upload those embeddings to the vector database to keep the pipeline modular and flexible; in the future we might want to use a different vector database so we can just swap out the upload step without having to re-generate the embeddings. In the next section, we'll explore how to store these embeddings in a vector database to enable fast and efficient retrieval of relevant chunks at inference time. ## Code Example To explore the full code, visit the [Complete Guide](https://github.com/zenml-io/zenml-projects/tree/main/llm-complete-guide) repository. The embeddings generation step can be found [here](https://github.com/zenml-io/zenml-projects/tree/main/llm-complete-guide/steps/populate_index.py).
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/rag-with-zenml/rag-85-loc.md ================ --- description: Learn how to implement a RAG pipeline in just 85 lines of code. --- There's a lot of theory and context to think about when it comes to RAG, but let's start with a quick implementation in code to motivate what follows. The following 85 lines do the following: - load some data (a fictional dataset about 'ZenML World') as our corpus - process that text (split it into chunks and 'tokenize' it (i.e. split into words)) - take a query as input and find the most relevant chunks of text from our corpus data - use OpenAI's GPT-3.5 model to answer the question based on the relevant chunks ```python import os import re import string from openai import OpenAI def preprocess_text(text): text = text.lower() text = text.translate(str.maketrans("", "", string.punctuation)) text = re.sub(r"\s+", " ", text).strip() return text def tokenize(text): return preprocess_text(text).split() def retrieve_relevant_chunks(query, corpus, top_n=2): query_tokens = set(tokenize(query)) similarities = [] for chunk in corpus: chunk_tokens = set(tokenize(chunk)) similarity = len(query_tokens.intersection(chunk_tokens)) / len( query_tokens.union(chunk_tokens) ) similarities.append((chunk, similarity)) similarities.sort(key=lambda x: x[1], reverse=True) return [chunk for chunk, _ in similarities[:top_n]] def answer_question(query, corpus, top_n=2): relevant_chunks = retrieve_relevant_chunks(query, corpus, top_n) if not relevant_chunks: return "I don't have enough information to answer the question." context = "\n".join(relevant_chunks) client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) chat_completion = client.chat.completions.create( messages=[ { "role": "system", "content": f"Based on the provided context, answer the following question: {query}\n\nContext:\n{context}", }, { "role": "user", "content": query, }, ], model="gpt-3.5-turbo", ) return chat_completion.choices[0].message.content.strip() # Sci-fi themed corpus about "ZenML World" corpus = [ "The luminescent forests of ZenML World are inhabited by glowing Zenbots that emit a soft, pulsating light as they roam the enchanted landscape.", "In the neon skies of ZenML World, Cosmic Butterflies flutter gracefully, their iridescent wings leaving trails of stardust in their wake.", "Telepathic Treants, ancient sentient trees, communicate through the quantum neural network that spans the entire surface of ZenML World, sharing wisdom and knowledge.", "Deep within the melodic caverns of ZenML World, Fractal Fungi emit pulsating tones that resonate through the crystalline structures, creating a symphony of otherworldly sounds.", "Near the ethereal waterfalls of ZenML World, Holographic Hummingbirds hover effortlessly, their translucent wings refracting the prismatic light into mesmerizing patterns.", "Gravitational Geckos, masters of anti-gravity, traverse the inverted cliffs of ZenML World, defying the laws of physics with their extraordinary abilities.", "Plasma Phoenixes, majestic creatures of pure energy, soar above the chromatic canyons of ZenML World, their fiery trails painting the sky in a dazzling display of colors.", "Along the prismatic shores of ZenML World, Crystalline Crabs scuttle and burrow, their transparent exoskeletons refracting the light into a kaleidoscope of hues.", ] corpus = [preprocess_text(sentence) for sentence in corpus] question1 = "What are Plasma Phoenixes?" answer1 = answer_question(question1, corpus) print(f"Question: {question1}") print(f"Answer: {answer1}") question2 = ( "What kinds of creatures live on the prismatic shores of ZenML World?" ) answer2 = answer_question(question2, corpus) print(f"Question: {question2}") print(f"Answer: {answer2}") irrelevant_question_3 = "What is the capital of Panglossia?" answer3 = answer_question(irrelevant_question_3, corpus) print(f"Question: {irrelevant_question_3}") print(f"Answer: {answer3}") ``` This outputs the following: ```shell Question: What are Plasma Phoenixes? Answer: Plasma Phoenixes are majestic creatures made of pure energy that soar above the chromatic canyons of Zenml World. They leave fiery trails behind them, painting the sky with dazzling displays of colors. Question: What kinds of creatures live on the prismatic shores of ZenML World? Answer: On the prismatic shores of ZenML World, you can find crystalline crabs scuttling and burrowing with their transparent exoskeletons, which refract light into a kaleidoscope of hues. Question: What is the capital of Panglossia? Answer: The capital of Panglossia is not mentioned in the provided context. ``` The implementation above is by no means sophisticated or performant, but it's simple enough that you can see all the moving parts. Our tokenization process consists of splitting the text into individual words. The way we check for similarity between the question / query and the chunks of text is extremely naive and inefficient. The similarity between the query and the current chunk is calculated using the [Jaccard similarity coefficient](https://www.statology.org/jaccard-similarity/). This coefficient measures the similarity between two sets and is defined as the size of the intersection divided by the size of the union of the two sets. So we count the number of words that are common between the query and the chunk and divide it by the total number of unique words in both the query and the chunk. There are much better ways of measuring the similarity between two pieces of text, such as using embeddings or other more sophisticated techniques, but this example is kept simple for illustrative purposes. The rest of this guide will showcase a more performant and scalable way of performing the same task using ZenML. If you ever are unsure why we're doing something, feel free to return to this example for the high-level overview.
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/rag-with-zenml/README.md ================ --- description: RAG is a sensible way to get started with LLMs. --- # RAG Pipelines with ZenML Retrieval-Augmented Generation (RAG) is a powerful technique that combines the strengths of retrieval-based and generation-based models. In this guide, we'll explore how to set up RAG pipelines with ZenML, including data ingestion, index store management, and tracking RAG-associated artifacts. LLMs are a powerful tool, as they can generate human-like responses to a wide variety of prompts. However, they can also be prone to generating incorrect or inappropriate responses, especially when the input prompt is ambiguous or misleading. They are also (currently) limited in the amount of text they can understand and/or generate. While there are some LLMs [like Google's Gemini 1.5 Pro](https://developers.googleblog.com/2024/02/gemini-15-available-for-private-preview-in-google-ai-studio.html) that can consistently handle 1 million tokens (small units of text), the vast majority (particularly the open-source ones currently available) handle far less. The first part of this guide to RAG pipelines with ZenML is about understanding the basic components and how they work together. We'll cover the following topics: - why RAG exists and what problem it solves - how to ingest and preprocess data that we'll use in our RAG pipeline - how to leverage embeddings to represent our data; this will be the basis for our retrieval mechanism - how to store these embeddings in a vector database - how to track RAG-associated artifacts with ZenML At the end, we'll bring it all together and show all the components working together to perform basic RAG inference.
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/rag-with-zenml/storing-embeddings-in-a-vector-database.md ================ --- description: Store embeddings in a vector database for efficient retrieval. --- # Storing embeddings in a vector database The process of generating the embeddings doesn't take too long, especially if the machine on which the step is running has a GPU, but it's still not something we want to do every time we need to retrieve a document. Instead, we can store the embeddings in a vector database, which allows us to quickly retrieve the most relevant chunks based on their similarity to the query. ![](../../../.gitbook/assets/rag-stage-3.png) For the purposes of this guide, we'll use PostgreSQL as our vector database. This is a popular choice for storing embeddings, as it provides a scalable and efficient way to store and retrieve high-dimensional vectors. However, you can use any vector database that supports high-dimensional vectors. If you want to explore a list of possible options, [this is a good website](https://superlinked.com/vector-db-comparison/) to compare different options. {% hint style="info" %} For more information on how to set up a PostgreSQL database to follow along with this guide, please [see the instructions in the repository](https://github.com/zenml-io/zenml-projects/tree/main/llm-complete-guide) which show how to set up a PostgreSQL database using Supabase. {% endhint %} Since PostgreSQL is a well-known and battle-tested database, we can use known and minimal packages to connect and to interact with it. We can use the [`psycopg2`](https://www.psycopg.org/docs/) package to connect and then raw SQL statements to interact with the database. The code for the step is fairly simple: ```python from zenml import step @step def index_generator( documents: List[Document], ) -> None: try: conn = get_db_conn() with conn.cursor() as cur: # Install pgvector if not already installed cur.execute("CREATE EXTENSION IF NOT EXISTS vector") conn.commit() # Create the embeddings table if it doesn't exist table_create_command = f""" CREATE TABLE IF NOT EXISTS embeddings ( id SERIAL PRIMARY KEY, content TEXT, token_count INTEGER, embedding VECTOR({EMBEDDING_DIMENSIONALITY}), filename TEXT, parent_section TEXT, url TEXT ); """ cur.execute(table_create_command) conn.commit() register_vector(conn) # Insert data only if it doesn't already exist for doc in documents: content = doc.page_content token_count = doc.token_count embedding = doc.embedding.tolist() filename = doc.filename parent_section = doc.parent_section url = doc.url cur.execute( "SELECT COUNT(*) FROM embeddings WHERE content = %s", (content,), ) count = cur.fetchone()[0] if count == 0: cur.execute( "INSERT INTO embeddings (content, token_count, embedding, filename, parent_section, url) VALUES (%s, %s, %s, %s, %s, %s)", ( content, token_count, embedding, filename, parent_section, url, ), ) conn.commit() cur.execute("SELECT COUNT(*) as cnt FROM embeddings;") num_records = cur.fetchone()[0] logger.info(f"Number of vector records in table: {num_records}") # calculate the index parameters according to best practices num_lists = max(num_records / 1000, 10) if num_records > 1000000: num_lists = math.sqrt(num_records) # use the cosine distance measure, which is what we'll later use for querying cur.execute( f"CREATE INDEX IF NOT EXISTS embeddings_idx ON embeddings USING ivfflat (embedding vector_cosine_ops) WITH (lists = {num_lists});" ) conn.commit() except Exception as e: logger.error(f"Error in index_generator: {e}") raise finally: if conn: conn.close() ``` We use some utility functions, but what we do here is: * connect to the database * create the `vector` extension if it doesn't already exist (this is to enable the vector data type in PostgreSQL) * create the `embeddings` table if it doesn't exist * insert the embeddings and documents into the table * calculate the index parameters according to best practices * create an index on the embeddings Note that we're inserting the documents into the embeddings table as well as the embeddings themselves. This is so that we can retrieve the documents based on their embeddings later on. It also helps with debugging from within the Supabase interface or wherever else we're examining the contents of the database. ![The Supabase editor interface](../../../.gitbook/assets/supabase-editor-interface.png) Deciding when to update your embeddings is a separate discussion and depends on the specific use case. If your data is frequently changing, and the changes are significant, you might want to fully reset the embeddings with each update. In other cases, you might just want to add new documents and embeddings into the database because the changes are minor or infrequent. In the code above, we choose to only add new embeddings if they don't already exist in the database. {% hint style="info" %} Depending on the size of your dataset and the number of embeddings you're storing, you might find that running this step on a CPU is too slow. In that case, you should ensure that this step runs on a GPU-enabled machine to speed up the process. You can do this with ZenML by using a step operator that runs on a GPU-enabled machine. See [the docs here](../../../component-guide/step-operators/step-operators.md) for more on how to set this up. {% endhint %} We also generate an index for the embeddings using the `ivfflat` method with the `vector_cosine_ops` operator. This is a common method for indexing high-dimensional vectors in PostgreSQL and is well-suited for similarity search using cosine distance. The number of lists is calculated based on the number of records in the table, with a minimum of 10 lists and a maximum of the square root of the number of records. This is a good starting point for tuning the index parameters, but you might want to experiment with different values to see how they affect the performance of your RAG pipeline. Now that we have our embeddings stored in a vector database, we can move on to the next step in the pipeline, which is to retrieve the most relevant documents based on a given query. This is where the real magic of the RAG pipeline comes into play, as we can use the embeddings to quickly retrieve the most relevant chunks of text based on their similarity to the query. This allows us to build a powerful and efficient question-answering system that can provide accurate and relevant responses to user queries in real-time. ## Code Example To explore the full code, visit the [Complete Guide](https://github.com/zenml-io/zenml-projects/tree/main/llm-complete-guide) repository. The logic for storing the embeddings in PostgreSQL can be found [here](https://github.com/zenml-io/zenml-projects/tree/main/llm-complete-guide/steps/populate\_index.py).
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/rag-with-zenml/understanding-rag.md ================ --- description: >- Understand the Retrieval-Augmented Generation (RAG) technique and its benefits. --- # Understanding Retrieval-Augmented Generation (RAG) LLMs are powerful but not without their limitations. They are prone to generating incorrect responses, especially when it's unclear what the input prompt is asking for. They are also limited in the amount of text they can understand and generate. While some LLMs can handle more than 1 million tokens of input, most open-source models can handle far less. Your use case also might not require all the complexity and cost associated with running a large LLM. RAG, [originally proposed in 2020](https://arxiv.org/abs/2005.11401v4) by researchers at Facebook, is a technique that supplements the inbuilt abilities of foundation models like LLMs with a retrieval mechanism. This mechanism retrieves relevant documents from a large corpus and uses them to generate a response. This approach combines the strengths of retrieval-based and generation-based models, allowing you to leverage the power of LLMs while addressing their limitations. ## What exactly happens in a RAG pipeline? ![](../../../.gitbook/assets/rag-process-whole.png) In a RAG pipeline, we use a retriever to find relevant documents from a large corpus and then uses a generator to produce a response based on the retrieved documents. This approach is particularly useful for tasks that require contextual understanding and long-form generation, such as question answering, summarization, and dialogue generation. RAG helps with the context limitations mentioned above by providing a way to retrieve relevant documents that can be used to generate a response. This retrieval step can help ensure that the generated response is grounded in relevant information, reducing the likelihood of generating incorrect or inappropriate responses. It also helps with the token limitations by allowing the generator to focus on a smaller set of relevant documents, rather than having to process an entire large corpus. Given the costs associated with running LLMs, RAG can also be more cost-effective than using a pure generation-based approach, as it allows you to focus the generator's resources on a smaller set of relevant documents. This can be particularly important when working with large corpora or when deploying models to resource-constrained environments. ## When is RAG a good choice? ![](../../../.gitbook/assets/rag-when.png) RAG is a good choice when you need to generate long-form responses that require contextual understanding and when you have access to a large corpus of relevant documents. It can be particularly useful for tasks like question answering, summarization, and dialogue generation, where the generated response needs to be grounded in relevant information. It's often the first thing that you'll want to try when dipping your toes into the world of LLMs. This is because it provides a sensible way to get a feel for how the process works, and it doesn't require as much data or computational resources as other approaches. It's also a good choice when you need to balance the benefits of LLMs with the limitations of the current generation of models. ## How does RAG fit into the ZenML ecosystem? In ZenML, you can set up RAG pipelines that combine the strengths of retrieval-based and generation-based models. This allows you to leverage the power of LLMs while addressing their limitations. ZenML provides tools for data ingestion, index store management, and tracking RAG-associated artifacts, making it easy to set up and manage RAG pipelines. ZenML also provides a way to scale beyond the limitations of simple RAG pipelines, as we shall see in later sections of this guide. While you might start off with something simple, at a later point you might want to transition to a more complex setup that involves finetuning embeddings, reranking retrieved documents, or even finetuning the LLM itself. ZenML provides tools for all of these scenarios, making it easy to scale your RAG pipelines as needed. ZenML allows you to track all the artifacts associated with your RAG pipeline, from hyperparameters and model weights to metadata and performance metrics, as well as all the RAG or LLM-specific artifacts like chains, agents, tokenizers and vector stores. These can all be tracked in the [Model Control Plane](../../../how-to/model-management-metrics/model-control-plane/README.md) and thus visualized in the [ZenML Pro](https://zenml.io/pro) dashboard. By bringing all of the above into a simple ZenML pipeline we achieve a clearly delineated set of steps that can be run and rerun to set up our basic RAG pipeline. This is a great starting point for building out more complex RAG pipelines, and it's a great way to get started with LLMs in a sensible way. A summary of some of the advantages that ZenML brings to the table here includes: * **Reproducibility**: You can rerun the pipeline to update the index store with new documents or to change the parameters of the chunking process and so on. Previous versions of the artifacts will be preserved, and you can compare the performance of different versions of the pipeline. * **Scalability**: You can easily scale the pipeline to handle larger corpora of documents by deploying it on a cloud provider and using a more scalable vector store. * **Tracking artifacts and associating them with metadata**: You can track the artifacts generated by the pipeline and associate them with metadata that provides additional context and insights into the pipeline. This metadata and these artifacts are then visible in the ZenML dashboard, allowing you to monitor the performance of the pipeline and debug any issues that arise. * **Maintainability** - Having your pipeline in a clear, modular format makes it easier to maintain and update. You can easily add new steps, change the parameters of existing steps, and experiment with different configurations to see how they affect the performance of the pipeline. * **Collaboration** - You can share the pipeline with your team and collaborate on it together. You can also use the ZenML dashboard to share insights and findings with your team, making it easier to work together on the pipeline. In the next section, we'll showcase the components of a basic RAG pipeline. This will give you a taste of how you can leverage the power of LLMs in your MLOps workflows using ZenML. Subsequent sections will cover more advanced topics like reranking retrieved documents, finetuning embeddings, and finetuning the LLM itself.
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/reranking/evaluating-reranking-performance.md ================ --- description: Evaluate the performance of your reranking model. --- # Evaluating reranking performance We've already set up an evaluation pipeline, so adding reranking evaluation is relatively straightforward. In this section, we'll explore how to evaluate the performance of your reranking model using ZenML. ### Evaluating Reranking Performance The simplest first step in evaluating the reranking model is to compare the retrieval performance before and after reranking. You can use the same metrics we discussed in the [evaluation section](../evaluation/) to assess the performance of the reranking model. ![](../../../.gitbook/assets/reranking-evaluation.png) If you recall, we have a hand-crafted set of queries and relevant documents that we use to evaluate the performance of our retrieval system. We also have a set that was [generated by LLMs](../evaluation/retrieval.md#automated-evaluation-using-synthetic-generated-queries). The actual retrieval test is implemented as follows: ```python def perform_retrieval_evaluation( sample_size: int, use_reranking: bool ) -> float: """Helper function to perform the retrieval evaluation.""" dataset = load_dataset("zenml/rag_qa_embedding_questions", split="train") sampled_dataset = dataset.shuffle(seed=42).select(range(sample_size)) total_tests = len(sampled_dataset) failures = 0 for item in sampled_dataset: generated_questions = item["generated_questions"] question = generated_questions[ 0 ] # Assuming only one question per item url_ending = item["filename"].split("/")[ -1 ] # Extract the URL ending from the filename # using the method above to query similar documents # we pass in whether we want to use reranking or not _, _, urls = query_similar_docs(question, url_ending, use_reranking) if all(url_ending not in url for url in urls): logging.error( f"Failed for question: {question}. Expected URL ending: {url_ending}. Got: {urls}" ) failures += 1 logging.info(f"Total tests: {total_tests}. Failures: {failures}") failure_rate = (failures / total_tests) * 100 return round(failure_rate, 2) ``` This function takes a sample size and a flag indicating whether to use reranking and evaluates the retrieval performance based on the generated questions and relevant documents. It queries similar documents for each question and checks whether the expected URL ending is present in the retrieved URLs. The failure rate is calculated as the percentage of failed tests over the total number of tests. This function is then called in two separate evaluation steps: one for the retrieval system without reranking and one for the retrieval system with reranking. ```python @step def retrieval_evaluation_full( sample_size: int = 100, ) -> Annotated[float, "full_failure_rate_retrieval"]: """Executes the retrieval evaluation step without reranking.""" failure_rate = perform_retrieval_evaluation( sample_size, use_reranking=False ) logging.info(f"Retrieval failure rate: {failure_rate}%") return failure_rate @step def retrieval_evaluation_full_with_reranking( sample_size: int = 100, ) -> Annotated[float, "full_failure_rate_retrieval_reranking"]: """Executes the retrieval evaluation step with reranking.""" failure_rate = perform_retrieval_evaluation( sample_size, use_reranking=True ) logging.info(f"Retrieval failure rate with reranking: {failure_rate}%") return failure_rate ``` Both of these steps return the failure rate of the respective retrieval systems. If we want, we can look into the logs of those steps (either on the dashboard or in the terminal) to see specific examples that failed. For example: ``` ... Loading default flashrank model for language en Default Model: ms-marco-MiniLM-L-12-v2 Loading FlashRankRanker model ms-marco-MiniLM-L-12-v2 Loading model FlashRank model ms-marco-MiniLM-L-12-v2... Running pairwise ranking.. Failed for question: Based on the provided ZenML documentation text, here's a question that can be asked: "How do I develop a custom alerter as described on the Feast page, and where can I find the 'How to use it?' guide?". Expected URL ending: feature-stores. Got: ['https://docs.zenml.io/stacks-and-components/component-guide/alerters/custom', 'https://docs.zenml.io/v/docs/stacks-and-components/component-guide/alerters/custom', 'https://docs.zenml.io/v/docs/reference/how-do-i', 'https://docs.zenml.io/stacks-and-components/component-guide/alerters', 'https://docs.zenml.io/stacks-and-components/component-guide/alerters/slack'] Loading default flashrank model for language en Default Model: ms-marco-MiniLM-L-12-v2 Loading FlashRankRanker model ms-marco-MiniLM-L-12-v2 Loading model FlashRank model ms-marco-MiniLM-L-12-v2... Running pairwise ranking.. Step retrieval_evaluation_full_with_reranking has finished in 4m20s. ``` We can see here a specific example of a failure in the reranking evaluation. It's quite a good one because we can see that the question asked was actually an anomaly in the sense that the LLM has generated two questions and included its meta-discussion of the two questions it generated. Obviously this is not a representative question for the dataset, and if we saw a lot of these we might want to take some time to both understand why the LLM is generating these questions and how we can filter them out. ### Visualizing our reranking performance Since ZenML can display visualizations in its dashboard, we can showcase the results of our experiments in a visual format. For example, we can plot the failure rates of the retrieval system with and without reranking to see the impact of reranking on the performance. Our documentation explains how to set up your outputs so that they appear as visualizations in the ZenML dashboard. You can find more information [here](../../../how-to/data-artifact-management/visualize-artifacts/README.md). There are lots of options, but we've chosen to plot our failure rates as a bar chart and export them as a `PIL.Image` object. We also plotted the other evaluation scores so as to get a quick global overview of our performance. ```python # passing the results from all our previous evaluation steps @step(enable_cache=False) def visualize_evaluation_results( small_retrieval_eval_failure_rate: float, small_retrieval_eval_failure_rate_reranking: float, full_retrieval_eval_failure_rate: float, full_retrieval_eval_failure_rate_reranking: float, failure_rate_bad_answers: float, failure_rate_bad_immediate_responses: float, failure_rate_good_responses: float, average_toxicity_score: float, average_faithfulness_score: float, average_helpfulness_score: float, average_relevance_score: float, ) -> Optional[Image.Image]: """Visualizes the evaluation results.""" step_context = get_step_context() pipeline_run_name = step_context.pipeline_run.name normalized_scores = [ score / 20 for score in [ small_retrieval_eval_failure_rate, small_retrieval_eval_failure_rate_reranking, full_retrieval_eval_failure_rate, full_retrieval_eval_failure_rate_reranking, failure_rate_bad_answers, ] ] scores = normalized_scores + [ failure_rate_bad_immediate_responses, failure_rate_good_responses, average_toxicity_score, average_faithfulness_score, average_helpfulness_score, average_relevance_score, ] labels = [ "Small Retrieval Eval Failure Rate", "Small Retrieval Eval Failure Rate Reranking", "Full Retrieval Eval Failure Rate", "Full Retrieval Eval Failure Rate Reranking", "Failure Rate Bad Answers", "Failure Rate Bad Immediate Responses", "Failure Rate Good Responses", "Average Toxicity Score", "Average Faithfulness Score", "Average Helpfulness Score", "Average Relevance Score", ] # Create a new figure and axis fig, ax = plt.subplots(figsize=(10, 6)) # Plot the horizontal bar chart y_pos = np.arange(len(labels)) ax.barh(y_pos, scores, align="center") ax.set_yticks(y_pos) ax.set_yticklabels(labels) ax.invert_yaxis() # Labels read top-to-bottom ax.set_xlabel("Score") ax.set_xlim(0, 5) ax.set_title(f"Evaluation Metrics for {pipeline_run_name}") # Adjust the layout plt.tight_layout() # Save the plot to a BytesIO object buf = io.BytesIO() plt.savefig(buf, format="png") buf.seek(0) image = Image.open(buf) return image ``` For one of my runs of the evaluation pipeline, this looked like the following in the dashboard: ![Evaluation metrics for our RAG pipeline](../../../.gitbook/assets/reranker\_evaluation\_metrics.png) You can see that for the full retrieval evaluation we do see an improvement. Our small retrieval test, which as of writing only included five questions, showed a considerable degradation in performance. Since these were specific examples where we knew the answers, this would be something we'd want to look into to see why the reranking model was not performing as expected. We can also see that regardless of whether reranking was performed or not, the retrieval scores aren't great. This is a good indication that we might want to look into the retrieval model itself (i.e. our embeddings) to see if we can improve its performance. This is what we'll turn to next as we explore finetuning our embeddings to improve retrieval performance. ### Try it out! To see how this works in practice, you can run the evaluation pipeline using the project code. The reranking is included as part of the pipeline, so providing you've run the main `rag` pipeline, you can run the evaluation pipeline to see how the reranking model is performing. To run the evaluation pipeline, first clone the project repository: ```bash git clone https://github.com/zenml-io/zenml-projects.git ``` Then navigate to the `llm-complete-guide` directory and follow the instructions in the `README.md` file to run the evaluation pipeline. (You'll have to have first run the main pipeline to generate the embeddings.) To run the evaluation pipeline, you can use the following command: ```bash python run.py --evaluation ``` This will run the evaluation pipeline and output the results to the dashboard. As always, you can inspect the progress, logs, and results in the dashboard!
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/reranking/implementing-reranking.md ================ --- description: Learn how to implement reranking in ZenML. --- # Implementing Reranking in ZenML We already have a working RAG pipeline, so inserting a reranker into the pipeline is relatively straightforward. The reranker will take the retrieved documents from the initial retrieval step and reorder them in terms of the query that was used to retrieve them. ![](/docs/book/.gitbook/assets/reranking-workflow.png) ## How and where to add reranking We'll use the [`rerankers`](https://github.com/AnswerDotAI/rerankers/) package to handle the reranking process in our RAG inference pipeline. It's a relatively low-cost (in terms of technical debt and complexity) and lightweight dependency to add into our pipeline. It offers an interface to most of the model types that are commonly used for reranking and means we don't have to worry about the specifics of each model. This package provides a `Reranker` abstract class that you can use to define your own reranker. You can also use the provided implementations to add reranking to your pipeline. The reranker takes the query and a list of retrieved documents as input and outputs a reordered list of documents based on the reranking scores. Here's a toy example: ```python from rerankers import Reranker ranker = Reranker('cross-encoder') texts = [ "I like to play soccer", "I like to play football", "War and Peace is a great book" "I love dogs", "Ginger cats aren't very smart", "I like to play basketball", ] results = ranker.rank(query="What's your favorite sport?", docs=texts) ``` And results will look something like this: ``` RankedResults( results=[ Result(doc_id=5, text='I like to play basketball', score=-0.46533203125, rank=1), Result(doc_id=0, text='I like to play soccer', score=-0.7353515625, rank=2), Result(doc_id=1, text='I like to play football', score=-0.9677734375, rank=3), Result(doc_id=2, text='War and Peace is a great book', score=-5.40234375, rank=4), Result(doc_id=3, text='I love dogs', score=-5.5859375, rank=5), Result(doc_id=4, text="Ginger cats aren't very smart", score=-5.94921875, rank=6) ], query="What's your favorite sport?", has_scores=True ) ``` We can see that the reranker has reordered the documents based on the reranking scores, with the most relevant document appearing at the top of the list. The texts about sport are at the top and the less relevant ones about animals are down at the bottom. We specified that we want a `cross-encoder` reranker, but you can also use other reranker models from the Hugging Face Hub, use API-driven reranker models (from Jina or Cohere, for example), or even define your own reranker model. Read [their documentation](https://github.com/AnswerDotAI/rerankers/) to see how to use these different configurations. In our case, we can simply add a helper function that can optionally be invoked when we want to use the reranker: ```python def rerank_documents( query: str, documents: List[Tuple], reranker_model: str = "flashrank" ) -> List[Tuple[str, str]]: """Reranks the given documents based on the given query.""" ranker = Reranker(reranker_model) docs_texts = [f"{doc[0]} PARENT SECTION: {doc[2]}" for doc in documents] results = ranker.rank(query=query, docs=docs_texts) # pair the texts with the original urls in `documents` # `documents` is a tuple of (content, url) # we want the urls to be returned reranked_documents_and_urls = [] for result in results.results: # content is a `rerankers` Result object index_val = result.doc_id doc_text = result.text doc_url = documents[index_val][1] reranked_documents_and_urls.append((doc_text, doc_url)) return reranked_documents_and_urls ``` This function takes a query and a list of documents (each document is a tuple of content and URL) and reranks the documents based on the query. It returns a list of tuples, where each tuple contains the reranked document text and the URL of the original document. We use the `flashrank` model from the `rerankers` package by default as it appeared to be a good choice for our use case during development. This function then gets used in tests in the following way: ```python def query_similar_docs( question: str, url_ending: str, use_reranking: bool = False, returned_sample_size: int = 5, ) -> Tuple[str, str, List[str]]: """Query similar documents for a given question and URL ending.""" embedded_question = get_embeddings(question) db_conn = get_db_conn() num_docs = 20 if use_reranking else returned_sample_size # get (content, url) tuples for the top n similar documents top_similar_docs = get_topn_similar_docs( embedded_question, db_conn, n=num_docs, include_metadata=True ) if use_reranking: reranked_docs_and_urls = rerank_documents(question, top_similar_docs)[ :returned_sample_size ] urls = [doc[1] for doc in reranked_docs_and_urls] else: urls = [doc[1] for doc in top_similar_docs] # Unpacking URLs return (question, url_ending, urls) ``` We get the embeddings for the question being passed into the function and connect to our PostgreSQL database. If we're using reranking, we get the top 20 documents similar to our query and rerank them using the `rerank_documents` helper function. We then extract the URLs from the reranked documents and return them. Note that we only return 5 URLs, but in the case of reranking we get a larger number of documents and URLs back from the database to pass to our reranker, but in the end we always choose the top five reranked documents to return. Now that we've added reranking to our pipeline, we can evaluate the performance of our reranker and see how it affects the quality of the retrieved documents. ## Code Example To explore the full code, visit the [Complete Guide](https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/) repository and for this section, particularly [the `eval_retrieval.py` file](https://github.com/zenml-io/zenml-projects/blob/main/llm-complete-guide/steps/eval_retrieval.py).
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/reranking/README.md ================ --- description: Add reranking to your RAG inference for better retrieval performance. --- Rerankers are a crucial component of retrieval systems that use LLMs. They help improve the quality of the retrieved documents by reordering them based on additional features or scores. In this section, we'll explore how to add a reranker to your RAG inference pipeline in ZenML. In previous sections, we set up the overall workflow, from data ingestion and preprocessing to embeddings generation and retrieval. We then set up some basic evaluation metrics to assess the performance of our retrieval system. A reranker is a way to squeeze a bit of extra performance out of the system by reordering the retrieved documents based on additional features or scores. ![](/docs/book/.gitbook/assets/reranking-workflow.png) As you can see, reranking is an optional addition we make to what we've already set up. It's not strictly necessary, but it can help improve the relevance and quality of the retrieved documents, which in turn can lead to better responses from the LLM. Let's dive in!
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/reranking/reranking.md ================ --- description: Add reranking to your RAG inference for better retrieval performance. --- Rerankers are a crucial component of retrieval systems that use LLMs. They help improve the quality of the retrieved documents by reordering them based on additional features or scores. In this section, we'll explore how to add a reranker to your RAG inference pipeline in ZenML. In previous sections, we set up the overall workflow, from data ingestion and preprocessing to embeddings generation and retrieval. We then set up some basic evaluation metrics to assess the performance of our retrieval system. A reranker is a way to squeeze a bit of extra performance out of the system by reordering the retrieved documents based on additional features or scores. ![](/docs/book/.gitbook/assets/reranking-workflow.png) As you can see, reranking is an optional addition we make to what we've already set up. It's not strictly necessary, but it can help improve the relevance and quality of the retrieved documents, which in turn can lead to better responses from the LLM. Let's dive in!
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/reranking/understanding-reranking.md ================ --- description: Understand how reranking works. --- ## What is reranking? Reranking is the process of refining the initial ranking of documents retrieved by a retrieval system. In the context of Retrieval-Augmented Generation (RAG), reranking plays a crucial role in improving the relevance and quality of the retrieved documents that are used to generate the final output. The initial retrieval step in RAG typically uses a sparse retrieval method, such as BM25 or TF-IDF, to quickly find a set of potentially relevant documents based on the input query. However, these methods rely on lexical matching and may not capture the semantic meaning or context of the query effectively. Rerankers, on the other hand, are designed to reorder the retrieved documents by considering additional features, such as semantic similarity, relevance scores, or domain-specific knowledge. They aim to push the most relevant and informative documents to the top of the list, ensuring that the LLM has access to the best possible context for generating accurate and coherent responses. ## Types of Rerankers There are different types of rerankers that can be used in RAG, each with its own strengths and trade-offs: 1. **Cross-Encoders**: Cross-encoders are a popular choice for reranking in RAG. They take the concatenated query and document as input and output a relevance score. Examples include BERT-based models fine-tuned for passage ranking tasks. Cross-encoders can capture the interaction between the query and document effectively but are computationally expensive. 2. **Bi-Encoders**: Bi-encoders, also known as dual encoders, use separate encoders for the query and document. They generate embeddings for the query and document independently and then compute the similarity between them. Bi-encoders are more efficient than cross-encoders but may not capture the query-document interaction as effectively. 3. **Lightweight Models**: Lightweight rerankers, such as distilled models or small transformer variants, aim to strike a balance between effectiveness and efficiency. They are faster and have a smaller footprint compared to large cross-encoders, making them suitable for real-time applications. ## Benefits of Reranking in RAG Reranking offers several benefits in the context of RAG: 1. **Improved Relevance**: By considering additional features and scores, rerankers can identify the most relevant documents for a given query, ensuring that the LLM has access to the most informative context for generating accurate responses. 2. **Semantic Understanding**: Rerankers can capture the semantic meaning and context of the query and documents, going beyond simple keyword matching. This enables the retrieval of documents that are semantically similar to the query, even if they don't contain exact keyword matches. 3. **Domain Adaptation**: Rerankers can be fine-tuned on domain-specific data to incorporate domain knowledge and improve performance in specific verticals or industries. 4. **Personalization**: Rerankers can be personalized based on user preferences, historical interactions, or user profiles, enabling the retrieval of documents that are more tailored to individual users' needs. In the next section, we'll dive into how to implement reranking in ZenML and integrate it into your RAG inference pipeline.
ZenML Scarf
================ File: docs/book/user-guide/llmops-guide/README.md ================ --- icon: robot description: Leverage the power of LLMs in your MLOps workflows with ZenML. --- # LLMOps guide Welcome to the ZenML LLMOps Guide, where we dive into the exciting world of Large Language Models (LLMs) and how to integrate them seamlessly into your MLOps pipelines using ZenML. This guide is designed for ML practitioners and MLOps engineers looking to harness the potential of LLMs while maintaining the robustness and scalability of their workflows.

ZenML simplifies the development and deployment of LLM-powered MLOps pipelines.

In this guide, we'll explore various aspects of working with LLMs in ZenML, including: * [RAG with ZenML](rag-with-zenml/README.md) * [RAG in 85 lines of code](rag-with-zenml/rag-85-loc.md) * [Understanding Retrieval-Augmented Generation (RAG)](rag-with-zenml/understanding-rag.md) * [Data ingestion and preprocessing](rag-with-zenml/data-ingestion.md) * [Embeddings generation](rag-with-zenml/embeddings-generation.md) * [Storing embeddings in a vector database](rag-with-zenml/storing-embeddings-in-a-vector-database.md) * [Basic RAG inference pipeline](rag-with-zenml/basic-rag-inference-pipeline.md) * [Evaluation and metrics](evaluation/README.md) * [Evaluation in 65 lines of code](evaluation/evaluation-in-65-loc.md) * [Retrieval evaluation](evaluation/retrieval.md) * [Generation evaluation](evaluation/generation.md) * [Evaluation in practice](evaluation/evaluation-in-practice.md) * [Reranking for better retrieval](reranking/README.md) * [Understanding reranking](reranking/understanding-reranking.md) * [Implementing reranking in ZenML](reranking/implementing-reranking.md) * [Evaluating reranking performance](reranking/evaluating-reranking-performance.md) * [Improve retrieval by finetuning embeddings](finetuning-embeddings/finetuning-embeddings.md) * [Synthetic data generation](finetuning-embeddings/synthetic-data-generation.md) * [Finetuning embeddings with Sentence Transformers](finetuning-embeddings/finetuning-embeddings-with-sentence-transformers.md) * [Evaluating finetuned embeddings](finetuning-embeddings/evaluating-finetuned-embeddings.md) * [Finetuning LLMs with ZenML](finetuning-llms/finetuning-llms.md) * [Finetuning in 100 lines of code](finetuning-llms/finetuning-100-loc.md) * [Why and when to finetune LLMs](finetuning-llms/why-and-when-to-finetune-llms.md) * [Starter choices with finetuning](finetuning-llms/starter-choices-for-finetuning-llms.md) * [Finetuning with 🤗 Accelerate](finetuning-llms/finetuning-with-accelerate.md) * [Evaluation for finetuning](finetuning-llms/evaluation-for-finetuning.md) * [Deploying finetuned models](finetuning-llms/deploying-finetuned-models.md) * [Next steps](finetuning-llms/next-steps.md) To follow along with the examples and tutorials in this guide, ensure you have a Python environment set up with ZenML installed. Familiarity with the concepts covered in the [Starter Guide](../starter-guide/README.md) and [Production Guide](../production-guide/README.md) is recommended. We'll showcase a specific application over the course of this LLM guide, showing how you can work from a simple RAG pipeline to a more complex setup that involves finetuning embeddings, reranking retrieved documents, and even finetuning the LLM itself. We'll do this all for a use case relevant to ZenML: a question answering system that can provide answers to common questions about ZenML. This will help you understand how to apply the concepts covered in this guide to your own projects. By the end of this guide, you'll have a solid understanding of how to leverage LLMs in your MLOps workflows using ZenML, enabling you to build powerful, scalable, and maintainable LLM-powered applications. First up, let's take a look at a super simple implementation of the RAG paradigm to get started.
ZenML Scarf
================ File: docs/book/user-guide/production-guide/ci-cd.md ================ --- description: >- Managing the lifecycle of a ZenML pipeline with Continuous Integration and Delivery --- # Set up CI/CD Until now, we have been executing ZenML pipelines locally. While this is a good mode of operating pipelines, in production it is often desirable to mediate runs through a central workflow engine baked into your CI. This allows data scientists to experiment with data processing and model training locally and then have code changes automatically tested and validated through the standard pull request/merge request peer review process. Changes that pass the CI and code review are then deployed automatically to production. Here is how this could look like: ![Pipeline being run on staging/production stack through ci/cd](../../.gitbook/assets/ci-cd-overall.png) ## Breaking it down To illustrate this, let's walk through how this process could be set up with a GitHub Repository. Basically we'll be using Github Actions in order to set up a proper CI/CD workflow. {% hint style="info" %} To see this in action, check out the [ZenML Gitflow Repository](https://github.com/zenml-io/zenml-gitflow/). This repository showcases how ZenML can be used for machine learning with a GitHub workflow that automates CI/CD with continuous model training and continuous model deployment to production. The repository is also meant to be used as a template: you can fork it and easily adapt it to your own MLOps stack, infrastructure, code and data.{% endhint %} ### Configure an API Key in ZenML In order to facilitate machine-to-machine connection you need to create an API key within ZenML. Learn more about those [here](../../how-to/manage-zenml-server/connecting-to-zenml/connect-with-a-service-account.md). ```bash zenml service-account create github_action_api_key ``` This will return the API Key to you like this. This will not be shown to you again, so make sure to copy it here for use in the next section. ```bash Created service account 'github_action_api_key'. Successfully created API key `default`. The API key value is: 'ZENKEY_...' Please store it safely as it will not be shown again. To configure a ZenML client to use this API key, run: ... ``` ### Set up your secrets in Github For our Github Actions we will need to set up some secrets [for our repository](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository). Specifically, you should use github secrets to store the `ZENML_API_KEY` that you created above. ![create_gh_secret.png](../../.gitbook/assets/create_gh_secret.png) The other values that are loaded from secrets into the environment [here](https://github.com/zenml-io/zenml-gitflow/blob/main/.github/workflows/pipeline_run.yaml#L14-L23) can also be set explicitly or as variables. ### (Optional) Set up different stacks for Staging and Production You might not necessarily want to use the same stack with the same resources for your staging and production use. This step is optional, all you'll need for certain is a stack that runs remotely (remote orchestration and artifact storage). The rest is up to you. You might for example want to parametrize your pipeline to use different data sources for the respective environments. You can also use different [configuration files](../../how-to/configuring-zenml/configuring-zenml.md) for the different environments to configure the [Model](../../how-to/model-management-metrics/model-control-plane/README.md), the [DockerSettings](../../how-to/customize-docker-builds/docker-settings-on-a-pipeline.md), the [ResourceSettings like accelerators](../../how-to/pipeline-development/training-with-gpus/README.md) differently for the different environments. ### Trigger a pipeline on a Pull Request (Merge Request) One way to ensure only fully working code makes it into production, you should use a staging environment to test all the changes made to your code base and verify they work as intended. To do so automatically you should set up a github action workflow that runs your pipeline for you when you make changes to it. [Here](https://github.com/zenml-io/zenml-gitflow/blob/main/.github/workflows/pipeline_run.yaml) is an example that you can use. To only run the Github Action on a PR, you can configure the yaml like this ```yaml on: pull_request: branches: [ staging, main ] ``` When the workflow starts we want to set some important values. Here is a simplified version that you can use. ```yaml jobs: run-staging-workflow: runs-on: run-zenml-pipeline env: ZENML_STORE_URL: ${{ secrets.ZENML_HOST }} # Put your server url here ZENML_STORE_API_KEY: ${{ secrets.ZENML_API_KEY }} # Retrieves the api key for use ZENML_STACK: stack_name # Use this to decide which stack is used for staging ZENML_GITHUB_SHA: ${{ github.event.pull_request.head.sha }} ZENML_GITHUB_URL_PR: ${{ github.event.pull_request._links.html.href }} ``` After configuring these values so they apply to your specific situation the rest of the template should work as is for you. Specifically you will need to install all requirements, connect to your ZenML Server, set an active stack and run a pipeline within your github action. ```yaml steps: - name: Check out repository code uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: '3.9' - name: Install requirements run: | pip3 install -r requirements.txt - name: Confirm ZenML client is connected to ZenML server run: | zenml status - name: Set stack run: | zenml stack set ${{ env.ZENML_STACK }} - name: Run pipeline run: | python run.py \ --pipeline end-to-end \ --dataset production \ --version ${{ env.ZENML_GITHUB_SHA }} \ --github-pr-url ${{ env.ZENML_GITHUB_URL_PR }} ``` When you push to a branch now, that is within a Pull Request, this action will run automatically. ### (Optional) Comment Metrics onto the PR Finally you can configure your github action workflow to leave a report based on the pipeline that was run. Check out the template for this [here](https://github.com/zenml-io/zenml-gitflow/blob/main/.github/workflows/pipeline_run.yaml#L87-L99. ![Comment left on Pull Request](../../.gitbook/assets/github-action-pr-comment.png)
ZenML Scarf
================ File: docs/book/user-guide/production-guide/cloud-orchestration.md ================ --- description: Orchestrate using cloud resources. --- # Orchestrate on the cloud Until now, we've only run pipelines locally. The next step is to get free from our local machines and transition our pipelines to execute on the cloud. This will enable you to run your MLOps pipelines in a cloud environment, leveraging the scalability and robustness that cloud platforms offer. In order to do this, we need to get familiar with two more stack components: * The [orchestrator](../../component-guide/orchestrators/orchestrators.md) manages the workflow and execution of your pipelines. * The [container registry](../../component-guide/container-registries/container-registries.md) is a storage and content delivery system that holds your Docker container images. These, along with [remote storage](remote-storage.md), complete a basic cloud stack where our pipeline is entirely running on the cloud. {% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already? 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 Terraform modules](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register a cloud stack. {% endhint %} ## Starting with a basic cloud stack The easiest cloud orchestrator to start with is the [Skypilot](https://skypilot.readthedocs.io/) orchestrator running on a public cloud. The advantage of Skypilot is that it simply provisions a VM to execute the pipeline on your cloud provider. Coupled with Skypilot, we need a mechanism to package your code and ship it to the cloud for Skypilot to do its thing. ZenML uses [Docker](https://www.docker.com/) to achieve this. Every time you run a pipeline with a remote orchestrator, [ZenML builds an image](../../how-to/project-setup-and-management/setting-up-a-project-repository/connect-your-git-repository.md) for the entire pipeline (and optionally each step of a pipeline depending on your [configuration](../../how-to/customize-docker-builds/README.md)). This image contains the code, requirements, and everything else needed to run the steps of the pipeline in any environment. ZenML then pushes this image to the container registry configured in your stack, and the orchestrator pulls the image when it's ready to execute a step. To summarize, here is the broad sequence of events that happen when you run a pipeline with such a cloud stack:

Sequence of events that happen when running a pipeline on a full cloud stack.

1. The user runs a pipeline on the client machine. This executes the `run.py` script where ZenML reads the `@pipeline` function and understands what steps need to be executed. 2. The client asks the server for the stack info, which returns it with the configuration of the cloud stack. 3. Based on the stack info and pipeline specification, the client builds and pushes an image to the `container registry`. The image contains the environment needed to execute the pipeline and the code of the steps. 4. The client creates a run in the `orchestrator`. For example, in the case of the [Skypilot](https://skypilot.readthedocs.io/) orchestrator, it creates a virtual machine in the cloud with some commands to pull and run a Docker image from the specified container registry. 5. The `orchestrator` pulls the appropriate image from the `container registry` as it's executing the pipeline (each step has an image). 6. As each pipeline runs, it stores artifacts physically in the `artifact store`. Of course, this artifact store needs to be some form of cloud storage. 7. As each pipeline runs, it reports status back to the ZenML server and optionally queries the server for metadata. ## Provisioning and registering an orchestrator alongside a container registry While there are detailed docs on [how to set up a Skypilot orchestrator](../../component-guide/orchestrators/skypilot-vm.md) and a [container registry](../../component-guide/container-registries/container-registries.md) on each public cloud, we have put the most relevant details here for convenience: {% tabs %} {% tab title="AWS" %} In order to launch a pipeline on AWS with the SkyPilot orchestrator, the first thing that you need to do is to install the AWS and Skypilot integrations: ```shell zenml integration install aws skypilot_aws -y ``` Before we start registering any components, there is another step that we have to execute. As we [explained in the previous section](remote-storage.md#configuring-permissions-with-your-first-service-connector), components such as orchestrators and container registries often require you to set up the right permissions. In ZenML, this process is simplified with the use of [Service Connectors](../../how-to/infrastructure-deployment/auth-management/README.md). For this example, we need to use the [IAM role authentication method of our AWS service connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md#aws-iam-role): ```shell AWS_PROFILE= zenml service-connector register cloud_connector --type aws --auto-configure ``` Once the service connector is set up, we can register [a Skypilot orchestrator](../../component-guide/orchestrators/skypilot-vm.md): ```shell zenml orchestrator register cloud_orchestrator -f vm_aws zenml orchestrator connect cloud_orchestrator --connector cloud_connector ``` The next step is to register [an AWS container registry](../../component-guide/container-registries/aws.md). Similar to the orchestrator, we will use our connector as we are setting up the container registry: ```shell zenml container-registry register cloud_container_registry -f aws --uri=.dkr.ecr..amazonaws.com zenml container-registry connect cloud_container_registry --connector cloud_connector ``` With the components registered, everything is set up for the next steps. For more information, you can always check the [dedicated Skypilot orchestrator guide](../../component-guide/orchestrators/skypilot-vm.md). {% endtab %} {% tab title="GCP" %} In order to launch a pipeline on GCP with the SkyPilot orchestrator, the first thing that you need to do is to install the GCP and Skypilot integrations: ```shell zenml integration install gcp skypilot_gcp -y ``` Before we start registering any components, there is another step that we have to execute. As we [explained in the previous section](remote-storage.md#configuring-permissions-with-your-first-service-connector), components such as orchestrators and container registries often require you to set up the right permissions. In ZenML, this process is simplified with the use of [Service Connectors](../../how-to/infrastructure-deployment/auth-management/README.md). For this example, we need to use the [Service Account authentication feature of our GCP service connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md#gcp-service-account): ```shell zenml service-connector register cloud_connector --type gcp --auth-method service-account --service_account_json=@ --project_id= --generate_temporary_tokens=False ``` Once the service connector is set up, we can register [a Skypilot orchestrator](../../component-guide/orchestrators/skypilot-vm.md): ```shell zenml orchestrator register cloud_orchestrator -f vm_gcp zenml orchestrator connect cloud_orchestrator --connect cloud_connector ``` The next step is to register [a GCP container registry](../../component-guide/container-registries/gcp.md). Similar to the orchestrator, we will use our connector as we are setting up the container registry: ```shell zenml container-registry register cloud_container_registry -f gcp --uri=gcr.io/ zenml container-registry connect cloud_container_registry --connector cloud_connector ``` With the components registered, everything is set up for the next steps. For more information, you can always check the [dedicated Skypilot orchestrator guide](../../component-guide/orchestrators/skypilot-vm.md). {% endtab %} {% tab title="Azure" %} As of [v0.60.0](https://github.com/zenml-io/zenml/releases/tag/0.60.0), alongside the switch to `pydantic` v2, due to an incompatibility between the new version `pydantic` and the `azurecli`, the `skypilot[azure]` flavor can not be installed at the same time. Therefore, for Azure users, an alternative is to use the [Kubernetes Orchestrator](../../component-guide/orchestrators/kubernetes.md). You can easily deploy a Kubernetes cluster in your subscription using the [Azure Kubernetes Service](https://azure.microsoft.com/en-us/products/kubernetes-service). In order to launch a pipeline on Azure with the Kubernetes orchestrator, the first thing that you need to do is to install the Azure and Kubernetes integrations: ```shell zenml integration install azure kubernetes -y ``` You should also ensure you have [kubectl installed](https://kubernetes.io/docs/tasks/tools/). Before we start registering any components, there is another step that we have to execute. As we [explained in the previous section](remote-storage.md#configuring-permissions-with-your-first-service-connector), components such as orchestrators and container registries often require you to set up the right permissions. In ZenML, this process is simplified with the use of [Service Connectors](../../how-to/infrastructure-deployment/auth-management/README.md). For this example, we will need to use the [Service Principal authentication feature of our Azure service connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md#azure-service-principal): ```shell zenml service-connector register cloud_connector --type azure --auth-method service-principal --tenant_id= --client_id= --client_secret= ``` Once the service connector is set up, we can register [a Kubernetes orchestrator](../../component-guide/orchestrators/kubernetes.md): ```shell # Ensure your service connector has access to the AKS cluster: zenml service-connector list-resources --resource-type kubernetes-cluster -e zenml orchestrator register cloud_orchestrator --flavor kubernetes zenml orchestrator connect cloud_orchestrator --connect cloud_connector ``` The next step is to register [an Azure container registry](../../component-guide/container-registries/azure.md). Similar to the orchestrator, we will use our connector as we are setting up the container registry. ```shell zenml container-registry register cloud_container_registry -f azure --uri=.azurecr.io zenml container-registry connect cloud_container_registry --connector cloud_connector ``` With the components registered, everything is set up for the next steps. For more information, you can always check the [dedicated Kubernetes orchestrator guide](../../component-guide/orchestrators/kubernetes.md). {% endtab %} {% endtabs %} {% hint style="info" %} Having trouble with setting up infrastructure? Try reading the [stack deployment](../../how-to/infrastructure-deployment/stack-deployment/README.md) section of the docs to gain more insight. If that still doesn't work, join the [ZenML community](https://zenml.io/slack) and ask! {% endhint %} ## Running a pipeline on a cloud stack Now that we have our orchestrator and container registry registered, we can [register a new stack](understand-stacks.md#registering-a-stack), just like we did in the previous chapter: {% tabs %} {% tab title="CLI" %} ```shell zenml stack register minimal_cloud_stack -o cloud_orchestrator -a cloud_artifact_store -c cloud_container_registry ``` {% endtab %} {% endtabs %} Now, using the [code from the previous chapter](understand-stacks.md#run-a-pipeline-on-the-new-local-stack), we can run a training pipeline. First, set the minimal cloud stack active: ```shell zenml stack set minimal_cloud_stack ``` and then, run the training pipeline: ```shell python run.py --training-pipeline ``` You will notice this time your pipeline behaves differently. After it has built the Docker image with all your code, it will push that image, and run a VM on the cloud. Here is where your pipeline will execute, and the logs will be streamed back to you. So with a few commands, we were able to ship our entire code to the cloud! Curious to see what other stacks you can create? The [Component Guide](../../component-guide/README.md) has an exhaustive list of various artifact stores, container registries, and orchestrators that are integrated with ZenML. Try playing around with more stack components to see how easy it is to switch between MLOps stacks with ZenML.
ZenML Scarf
================ File: docs/book/user-guide/production-guide/configure-pipeline.md ================ --- description: Add more resources to your pipeline configuration. --- # Configure your pipeline to add compute Now that we have our pipeline up and running in the cloud, you might be wondering how ZenML figured out what sort of dependencies to install in the Docker image that we just ran on the VM. The answer lies in the [runner script we executed (i.e. run.py)](https://github.com/zenml-io/zenml/blob/main/examples/quickstart/run.py#L215), in particular, these lines: ```python pipeline_args["config_path"] = os.path.join( config_folder, "training_rf.yaml" ) # Configure the pipeline training_pipeline_configured = training_pipeline.with_options(**pipeline_args) # Create a run training_pipeline_configured() ``` The above commands [configure our training pipeline](../starter-guide/create-an-ml-pipeline.md#configure-with-a-yaml-file) with a YAML configuration called `training_rf.yaml` (found [here in the source code](https://github.com/zenml-io/zenml/blob/main/examples/quickstart/configs/training\_rf.yaml)). Let's learn more about this configuration file. {% hint style="info" %} The `with_options` command that points to a YAML config is only one way to configure a pipeline. We can also directly configure a pipeline or a step in the decorator: ```python @pipeline(settings=...) ``` However, it is best to not mix configuration from code to ensure separation of concerns in our codebase. {% endhint %} ## Breaking down our configuration YAML The YAML configuration of a ZenML pipeline can be very simple, as in this case. Let's break it down and go through each section one by one: ### The Docker settings ```yaml settings: docker: required_integrations: - sklearn requirements: - pyarrow ``` The first section is the so-called `settings` of the pipeline. This section has a `docker` key, which controls the [containerization process](cloud-orchestration.md#orchestrating-pipelines-on-the-cloud). Here, we are simply telling ZenML that we need `pyarrow` as a pip requirement, and we want to enable the `sklearn` integration of ZenML, which will in turn install the `scikit-learn` library. This Docker section can be populated with many different options, and correspond to the [DockerSettings](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-config/#zenml.config.docker\_settings.DockerSettings) class in the Python SDK. ### Associating a ZenML Model The next section is about associating a [ZenML Model](../starter-guide/track-ml-models.md) with this pipeline. ```yaml # Configuration of the Model Control Plane model: name: breast_cancer_classifier version: rf license: Apache 2.0 description: A breast cancer classifier tags: ["breast_cancer", "classifier"] ``` You will see that this configuration lines up with the model created after executing these pipelines: {% tabs %} {% tab title="CLI" %} ```shell # List all versions of the breast_cancer_classifier zenml model version list breast_cancer_classifier ``` {% endtab %} {% tab title="Dashboard" %} [ZenML Pro](https://www.zenml.io/pro) ships with a Model Control Plane dashboard where you can visualize all the versions:

All model versions listed

{% endtab %} {% endtabs %} ### Passing parameters The last part of the config YAML is the `parameters` key: ```yaml # Configure the pipeline parameters: model_type: "rf" # Choose between rf/sgd ``` This parameters key aligns with the parameters that the pipeline expects. In this case, the pipeline expects a string called `model_type` that will inform it which type of model to use: ```python @pipeline def training_pipeline(model_type: str): ... ``` So you can see that the YAML config is fairly easy to use and is an important part of the codebase to control the execution of our pipeline. You can read more about how to configure a pipeline in the [how to section](../../how-to/pipeline-development/use-configuration-files/what-can-be-configured.md), but for now, we can move on to scaling our pipeline. ## Scaling compute on the cloud When we ran our pipeline with the above config, ZenML used some sane defaults to pick the resource requirements for that pipeline. However, in the real world, you might want to add more memory, CPU, or even a GPU depending on the pipeline at hand. This is as easy as adding the following section to your local `training_rf.yaml` file: ```yaml # These are the resources for the entire pipeline, i.e., each step settings: ... # Adapt this to vm_gcp accordingly orchestrator: memory: 32 # in GB ... steps: model_trainer: settings: orchestrator: cpus: 8 ``` Here we are configuring the entire pipeline with a certain amount of memory, while for the trainer step we are additionally configuring 8 CPU cores. The `orchestrator` key corresponds to the [`SkypilotBaseOrchestratorSettings`](https://sdkdocs.zenml.io/latest/integration\_code\_docs/integrations-skypilot/#zenml.integrations.skypilot.flavors.skypilot\_orchestrator\_base\_vm\_config.SkypilotBaseOrchestratorSettings) class in the Python SDK.
Instructions for Microsoft Azure Users As discussed [before](cloud-orchestration.md), we are using the [Kubernetes orchestrator](../../component-guide/orchestrators/kubernetes.md) for Azure users. In order to scale compute for the Kubernetes orchestrator, the YAML file needs to look like this: ```yaml # These are the resources for the entire pipeline, i.e., each step settings: ... resources: memory: "32GB" ... steps: model_trainer: settings: resources: memory: "8GB" ```
{% hint style="info" %} Read more about settings in ZenML [here](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md) and [here](../../how-to/pipeline-development/training-with-gpus/README.md) {% endhint %} Now let's run the pipeline again: ```python python run.py --training-pipeline ``` Now you should notice the machine that gets provisioned on your cloud provider would have a different configuration as compared to last time. As easy as that! Bear in mind that not every orchestrator supports `ResourceSettings` directly. To learn more, you can read about [`ResourceSettings` here](../../how-to/pipeline-development/use-configuration-files/runtime-configuration.md), including the ability to [attach a GPU](../../how-to/pipeline-development/training-with-gpus/README.md#1-specify-a-cuda-enabled-parent-image-in-your-dockersettings).
ZenML Scarf
================ File: docs/book/user-guide/production-guide/connect-code-repository.md ================ --- description: >- Connect a Git repository to ZenML to track code changes and collaborate on MLOps projects. --- # Configure a code repository Throughout the lifecycle of a MLOps pipeline, it can get quite tiresome to always wait for a Docker build every time after running a pipeline (even if the local Docker cache is used). However, there is a way to just have one pipeline build and keep reusing it until a change to the pipeline environment is made: by connecting a code repository. With ZenML, connecting to a Git repository optimizes the Docker build processes. It also has the added bonus of being a better way of managing repository changes and enabling better code collaboration. Here is how the flow changes when running a pipeline:

Sequence of events that happen when running a pipeline on a remote stack with a code repository

1. You trigger a pipeline run on your local machine. ZenML parses the `@pipeline` function to determine the necessary steps. 2. The local client requests stack information from the ZenML server, which responds with the cloud stack configuration. 3. The local client detects that we're using a code repository and requests the information from the git repo. 4. Instead of building a new Docker image, the client checks if an existing image can be reused based on the current Git commit hash and other environment metadata. 5. The client initiates a run in the orchestrator, which sets up the execution environment in the cloud, such as a VM. 6. The orchestrator downloads the code directly from the Git repository and uses the existing Docker image to run the pipeline steps. 7. Pipeline steps execute, storing artifacts in the cloud-based artifact store. 8. Throughout the execution, the pipeline run status and metadata are reported back to the ZenML server. By connecting a Git repository, you avoid redundant builds and make your MLOps processes more efficient. Your team can work on the codebase simultaneously, with ZenML handling the version tracking and ensuring that the correct code version is always used for each run. ## Creating a GitHub Repository While ZenML supports [many different flavors of git repositories](../../how-to/project-setup-and-management/setting-up-a-project-repository/connect-your-git-repository.md), this guide will focus on [GitHub](https://github.com). To create a repository on GitHub: 1. Sign in to [GitHub](https://github.com/). 2. Click the "+" icon and select "New repository." 3. Name your repository, set its visibility, and add a README or .gitignore if needed. 4. Click "Create repository." We can now push our local code (from the [previous chapters](understand-stacks.md#run-a-pipeline-on-the-new-local-stack)) to GitHub with these commands: ```sh # Initialize a Git repository git init # Add files to the repository git add . # Commit the files git commit -m "Initial commit" # Add the GitHub remote git remote add origin https://github.com/YOUR_USERNAME/YOUR_REPOSITORY_NAME.git # Push to GitHub git push -u origin master ``` Replace `YOUR_USERNAME` and `YOUR_REPOSITORY_NAME` with your GitHub information. ## Linking to ZenML To connect your GitHub repository to ZenML, you'll need a GitHub Personal Access Token (PAT).
How to get a PAT for GitHub 1. Go to your GitHub account settings and click on [Developer settings](https://github.com/settings/tokens?type=beta). 2. Select "Personal access tokens" and click on "Generate new token". 3. Give your token a name and a description. ![](../../.gitbook/assets/github-fine-grained-token-name.png) 4. We recommend selecting the specific repository and then giving `contents` read-only access. ![](../../.gitbook/assets/github-token-set-permissions.png) ![](../../.gitbook/assets/github-token-permissions-overview.png) 5. Click on "Generate token" and copy the token to a safe place. ![](../../.gitbook/assets/copy-github-fine-grained-token.png)
Now, we can install the GitHub integration and register your repository: ```sh zenml integration install github zenml code-repository register --type=github \ --url=https://github.com/YOUR_USERNAME/YOUR_REPOSITORY_NAME.git \ --owner=YOUR_USERNAME --repository=YOUR_REPOSITORY_NAME \ --token=YOUR_GITHUB_PERSONAL_ACCESS_TOKEN ``` Fill in ``, `YOUR_USERNAME`, `YOUR_REPOSITORY_NAME`, and `YOUR_GITHUB_PERSONAL_ACCESS_TOKEN` with your details. Your code is now connected to your ZenML server. ZenML will automatically detect if your source files are being tracked by GitHub and store the commit hash for each subsequent pipeline run. You can try this out by running our training pipeline again: ```python # This will build the Docker image the first time python run.py --training-pipeline # This will skip Docker building python run.py --training-pipeline ``` You can read more about [the ZenML Git Integration here](../../how-to/project-setup-and-management/setting-up-a-project-repository/connect-your-git-repository.md).
ZenML Scarf
================ File: docs/book/user-guide/production-guide/deploying-zenml.md ================ --- description: Deploying ZenML is the first step to production. --- # Deploying ZenML When you first get started with ZenML, it is based on the following architecture on your machine: ![Scenario 1: ZenML default local configuration](../../.gitbook/assets/Scenario1.png) The SQLite database that you can see in this diagram is used to store all the metadata we produced in the previous guide (pipelines, models, artifacts, etc). In order to move into production, you will need to deploy this server somewhere centrally outside of your machine. This allows different infrastructure components to interact with, alongside enabling you to collaborate with your team members: ![Scenario 3: Deployed ZenML Server](../../.gitbook/assets/Scenario3.2.png) ## Choosing how to deploy ZenML While there are many options on how to [deploy ZenML](../../getting-started/deploying-zenml/README.md), the two simplest ones are: ### Option 1: Sign up for a free ZenML Pro Trial [ZenML Pro](https://zenml.io/pro) comes as a managed SaaS solution that offers a one-click deployment for your ZenML server. If you have the ZenML Python client already installed, you can fast-track to connecting to a trial ZenML Pro instance by simply running: ```bash zenml login --pro ``` Alternatively, click [here](https://cloud.zenml.io/?utm\_source=docs\&utm\_medium=referral\_link\&utm\_campaign=cloud\_promotion\&utm\_content=signup\_link) to start a free trial. On top of the one-click SaaS experience, ZenML Pro also comes built-in with additional features and a new dashboard that might be beneficial to follow for this guide. You can always go back to self-hosting after your learning journey is complete. ### Option 2: Self-host ZenML on your cloud provider As ZenML is open source, it is easy to [self-host it](../../getting-started/deploying-zenml/README.md) in a Kubernetes cluster. If you don't have an existing Kubernetes cluster, you can create it manually using the documentation for your cloud provider. For convenience, here are links for [AWS](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html), [Azure](https://learn.microsoft.com/en-us/azure/aks/learn/quick-kubernetes-deploy-portal?tabs=azure-cli), and [GCP](https://cloud.google.com/kubernetes-engine/docs/how-to/creating-a-zonal-cluster#before\_you\_begin). To learn more about different options for [deploying ZenML, visit the deployment documentation](../../getting-started/deploying-zenml/README.md). ## Connecting to a deployed ZenML You can connect your local ZenML client with the ZenML Server using the ZenML CLI and the web-based login. This can be executed with the command: ```bash zenml login ``` {% hint style="info" %} Having trouble connecting with a browser? There are other ways to connect. Read [here](../../how-to/manage-zenml-server/connecting-to-zenml/README.md) for more details. {% endhint %} This command will start a series of steps to validate the device from where you are connecting that will happen in your browser. After that, you're now locally connected to a remote ZenML. Nothing of your experience changes, except that all metadata that you produce will be tracked centrally in one place from now on. {% hint style="info" %} You can always go back to the local zenml experience by using `zenml logout` {% endhint %} ## Further resources To learn more about deploying ZenML, check out the following resources: - [Deploying ZenML](../../getting-started/deploying-zenml/README.md): an overview of the different options for deploying ZenML and the system architecture of a deployed ZenML instance. - [Full how-to guides](../../getting-started/deploying-zenml/README.md): guides on how to deploy ZenML on Docker or Hugging Face Spaces or Kubernetes or some other cloud provider.
ZenML Scarf
================ File: docs/book/user-guide/production-guide/end-to-end.md ================ --- description: Put your new knowledge in action with an end-to-end project --- # An end-to-end project That was awesome! We learned so many advanced MLOps production concepts: * The value of [deploying ZenML](deploying-zenml.md) * Abstracting infrastructure configuration into [stacks](understand-stacks.md) * [Connecting remote storage](remote-storage.md) * [Orchestrating on the cloud](cloud-orchestration.md) * [Configuring the pipeline to scale compute](configure-pipeline.md) * [Connecting a git repository](connect-code-repository.md) We will now combine all of these concepts into an end-to-end MLOps project powered by ZenML. ## Get started Start with a fresh virtual environment with no dependencies. Then let's install our dependencies: ```bash pip install "zenml[templates,server]" notebook zenml integration install sklearn -y ``` We will then use [ZenML templates](../../how-to/project-setup-and-management/collaborate-with-team/project-templates/README.md) to help us get the code we need for the project: ```bash mkdir zenml_batch_e2e cd zenml_batch_e2e zenml init --template e2e_batch --template-with-defaults # Just in case, we install the requirements again pip install -r requirements.txt ```
Above doesn't work? Here is an alternative The e2e template is also available as a [ZenML example](https://github.com/zenml-io/zenml/tree/main/examples/e2e). You can clone it: ```bash git clone --depth 1 git@github.com:zenml-io/zenml.git cd zenml/examples/e2e pip install -r requirements.txt zenml init ```
## What you'll learn The e2e project is a comprehensive project template to cover major use cases of ZenML: a collection of steps and pipelines and, to top it all off, a simple but useful CLI. It showcases the core ZenML concepts for supervised ML with batch predictions. It builds on top of the [starter project](../starter-guide/starter-project.md) with more advanced concepts. As you progress through the e2e batch template, try running the pipelines on a [remote cloud stack](cloud-orchestration.md) on a tracked [git repository](connect-code-repository.md) to practice some of the concepts we have learned in this guide. At the end, don't forget to share the [ZenML e2e template](https://github.com/zenml-io/template-e2e-batch) with your colleagues and see how they react! ## Conclusion and next steps The production guide has now hopefully landed you with an end-to-end MLOps project, powered by a ZenML server connected to your cloud infrastructure. You are now ready to dive deep into writing your own pipelines and stacks. If you are looking to learn more advanced concepts, the [how-to section](../../how-to/pipeline-development/build-pipelines/README.md) is for you. Until then, we wish you the best of luck chasing your MLOps dreams!
ZenML Scarf
================ File: docs/book/user-guide/production-guide/README.md ================ --- icon: tree description: Level up your skills in a production setting. --- # Production guide The ZenML production guide builds upon the [Starter guide](../starter-guide/README.md) and is the next step in the MLOps Engineer journey with ZenML. If you're an ML practitioner hoping to implement a proof of concept within your workplace to showcase the importance of MLOps, this is the place for you.

ZenML simplifies development of MLOps pipelines that can span multiple production stacks.

This guide will focus on shifting gears from running pipelines _locally_ on your machine, to running them in _production_ in the cloud. We'll cover: * [Deploying ZenML](deploying-zenml.md) * [Understanding stacks](understand-stacks.md) * [Connecting remote storage](remote-storage.md) * [Orchestrating on the cloud](cloud-orchestration.md) * [Configuring the pipeline to scale compute](configure-pipeline.md) * [Configure a code repository](connect-code-repository.md) Like in the starter guide, make sure you have a Python environment ready and `virtualenv` installed to follow along with ease. As now we are dealing with cloud infrastructure, you'll also want to select one of the major cloud providers (AWS, GCP, Azure), and make sure the respective CLIs are installed and authorized. By the end, you will have completed an [end-to-end](end-to-end.md) MLOps project that you can use as inspiration for your own work. Let's get right into it!
ZenML Scarf
================ File: docs/book/user-guide/production-guide/remote-storage.md ================ --- description: Transitioning to remote artifact storage. --- # Connecting remote storage In the previous chapters, we've been working with artifacts stored locally on our machines. This setup is fine for individual experiments, but as we move towards a collaborative and production-ready environment, we need a solution that is more robust, shareable, and scalable. Enter remote storage! Remote storage allows us to store our artifacts in the cloud, which means they're accessible from anywhere and by anyone with the right permissions. This is essential for team collaboration and for managing the larger datasets and models that come with production workloads. When using a stack with remote storage, nothing changes except the fact that the artifacts get materialized in a central and remote storage location. This diagram explains the flow:

Sequence of events that happen when running a pipeline on a remote artifact store.

{% hint style="info" %} Would you like to skip ahead and deploy a full ZenML cloud stack already? 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 Terraform modules](../../how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) for a shortcut on how to deploy & register a cloud stack. {% endhint %} ## Provisioning and registering a remote artifact store Out of the box, ZenML ships with [many different supported artifact store flavors](../../component-guide/artifact-stores/artifact-stores.md). For convenience, here are some brief instructions on how to quickly get up and running on the major cloud providers: {% tabs %} {% tab title="AWS" %} 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. The Amazon Web Services S3 Artifact Store flavor is provided by the [S3 ZenML integration](../../component-guide/artifact-stores/s3.md), 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 ``` {% hint style="info" %} Having trouble with this command? You can use `poetry` or `pip` to install the requirements of any ZenML integration directly. In order to obtain the exact requirements of the AWS S3 integration you can use `zenml integration requirements s3`. {% endhint %} 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`. In order to create a S3 bucket, refer to the [AWS documentation](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 can be done as follows: ```shell # Register the S3 artifact-store zenml artifact-store register cloud_artifact_store -f s3 --path=s3://bucket-name ``` For more information, read the [dedicated S3 artifact store flavor guide](../../component-guide/artifact-stores/s3.md). {% endtab %} {% tab title="GCP" %} 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. The Google Cloud Storage Artifact Store flavor is provided by the [GCP ZenML integration](../../component-guide/artifact-stores/gcp.md), 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 ``` {% hint style="info" %} Having trouble with this command? You can use `poetry` or `pip` to install the requirements of any ZenML integration directly. In order to obtain the exact requirements of the GCP integrations you can use `zenml integration requirements gcp`. {% endhint %} 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 provision 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 cloud_artifact_store -f gcp --path=gs://bucket-name ``` For more information, read the [dedicated GCS artifact store flavor guide](../../component-guide/artifact-stores/gcp.md). {% endtab %} {% tab title="Azure" %} You will need to install and set up the Azure CLI on your machine as a prerequisite, as covered in [the Azure documentation](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli), before you register the Azure Artifact Store. The Microsoft Azure Artifact Store flavor is provided by the [Azure ZenML integration](../../component-guide/artifact-stores/azure.md), 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 ``` {% hint style="info" %} Having trouble with this command? You can use `poetry` or `pip` to install the requirements of any ZenML integration directly. In order to obtain the exact requirements of the Azure integration you can use `zenml integration requirements azure`. {% endhint %} 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 provision 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 cloud_artifact_store -f azure --path=az://container-name ``` For more information, read the [dedicated Azure artifact store flavor guide](../../component-guide/artifact-stores/azure.md). {% endtab %} {% tab title="Other" %} You can create a remote artifact store in pretty much any environment, including other cloud providers using a cloud-agnostic artifact storage such as [Minio](../../component-guide/artifact-stores/artifact-stores.md). It is also relatively simple to create a [custom stack component flavor](../../how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md) for your use case. {% endtab %} {% endtabs %} {% hint style="info" %} Having trouble with setting up infrastructure? Join the [ZenML community](https://zenml.io/slack) and ask for help! {% endhint %} ## Configuring permissions with your first service connector While you can go ahead and [run your pipeline on your stack](remote-storage.md#running-a-pipeline-on-a-cloud-stack) if your local client is configured to access it, it is best practice to use a [service connector](../../how-to/auth-management/) for this purpose. Service connectors are quite a complicated concept (We have a whole [docs section](../../how-to/auth-management/) on them) - but we're going to be starting with a very basic approach. First, let's understand what a service connector does. In simple words, a service connector contains credentials that grant stack components access to cloud infrastructure. These credentials are stored in the form of a [secret](../../how-to/project-setup-and-management/interact-with-secrets.md), and are available to the ZenML server to use. Using these credentials, the service connector brokers a short-lived token and grants temporary permissions to the stack component to access that infrastructure. This diagram represents this process:

Service Connectors abstract away complexity and implement security best practices

{% tabs %} {% tab title="AWS" %} There are [many ways to create an AWS service connector](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md#authentication-methods), but for the sake of this guide, we recommend creating one by [using the IAM method](../../how-to/infrastructure-deployment/auth-management/aws-service-connector.md#aws-iam-role). ```shell AWS_PROFILE= zenml service-connector register cloud_connector --type aws --auto-configure ``` {% endtab %} {% tab title="GCP" %} There are [many ways to create a GCP service connector](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md#authentication-methods), but for the sake of this guide, we recommend creating one by [using the Service Account method](../../how-to/infrastructure-deployment/auth-management/gcp-service-connector.md#gcp-service-account). ```shell zenml service-connector register cloud_connector --type gcp --auth-method service-account --service_account_json=@ --project_id= --generate_temporary_tokens=False ``` {% endtab %} {% tab title="Azure" %} There are [many ways to create an Azure service connector](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md#authentication-methods), but for the sake of this guide, we recommend creating one by [using the Service Principal method](../../how-to/infrastructure-deployment/auth-management/azure-service-connector.md#azure-service-principal). ```shell zenml service-connector register cloud_connector --type azure --auth-method service-principal --tenant_id= --client_id= --client_secret= ``` {% endtab %} {% endtabs %} Once we have our service connector, we can now attach it to stack components. In this case, we are going to connect it to our remote artifact store: ```shell zenml artifact-store connect cloud_artifact_store --connector cloud_connector ``` Now, every time you (or anyone else with access) uses the `cloud_artifact_store`, they will be granted a temporary token that will grant them access to the remote storage. Therefore, your colleagues don't need to worry about setting up credentials and installing clients locally! ## Running a pipeline on a cloud stack Now that we have our remote artifact store registered, we can [register a new stack](understand-stacks.md#registering-a-stack) with it, just like we did in the previous chapter: {% tabs %} {% tab title="CLI" %} ```shell zenml stack register local_with_remote_storage -o default -a cloud_artifact_store ``` {% endtab %} {% tab title="Dashboard" %}

Register a new stack.

{% endtab %} {% endtabs %} Now, using the [code from the previous chapter](understand-stacks.md#run-a-pipeline-on-the-new-local-stack), we run a training pipeline: Set our `local_with_remote_storage` stack active: ```shell zenml stack set local_with_remote_storage ``` Let us continue with the example from the previous page and run the training pipeline: ```shell python run.py --training-pipeline ``` When you run that pipeline, ZenML will automatically store the artifacts in the specified remote storage, ensuring that they are preserved and accessible for future runs and by your team members. You can ask your colleagues to connect to the same [ZenML server](deploying-zenml.md), and you will notice that if they run the same pipeline, the pipeline would be partially cached, **even if they have not run the pipeline themselves before**. You can list your artifact versions as follows: {% tabs %} {% tab title="CLI" %} ```shell # This will give you the artifacts from the last 15 minutes zenml artifact version list --created="gte:$(date -v-15M '+%Y-%m-%d %H:%M:%S')" ``` {% endtab %} {% tab title="Cloud Dashboard" %} [ZenML Pro](https://zenml.io/pro) features an [Artifact Control Plane](../starter-guide/manage-artifacts.md) to visualize artifact versions:

See artifact versions in the cloud.

{% endtab %} {% endtabs %} You will notice above that some artifacts are stored locally, while others are stored in a remote storage location. By connecting remote storage, you're taking a significant step towards building a collaborative and scalable MLOps workflow. Your artifacts are no longer tied to a single machine but are now part of a cloud-based ecosystem, ready to be shared and built upon.
ZenML Scarf
================ File: docs/book/user-guide/production-guide/understand-stacks.md ================ --- description: Learning how to switch the infrastructure backend of your code. --- # Understanding stacks Now that we have ZenML deployed, we can take the next steps in making sure that our machine learning workflows are production-ready. As you were running [your first pipelines](../starter-guide/create-an-ml-pipeline.md), you might have already noticed the term `stack` in the logs and on the dashboard. A `stack` is the configuration of tools and infrastructure that your pipelines can run on. When you run ZenML code without configuring a stack, the pipeline will run on the so-called `default` stack.

ZenML is the translation layer that allows your code to run on any of your stacks

### Separation of code from configuration and infrastructure As visualized in the diagram above, there are two separate domains that are connected through ZenML. The left side shows the code domain. The user's Python code is translated into a ZenML pipeline. On the right side, you can see the infrastructure domain, in this case, an instance of the `default` stack. By separating these two domains, it is easy to switch the environment that the pipeline runs on without making any changes in the code. It also allows domain experts to write code/configure infrastructure without worrying about the other domain. {% hint style="info" %} You can get the `pip` requirements of your stack by running the `zenml stack export-requirements ` CLI command. {% endhint %} ### The `default` stack `zenml stack describe` lets you find out details about your active stack: ```bash ... Stack Configuration ┏━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓ ┃ COMPONENT_TYPE │ COMPONENT_NAME ┃ ┠────────────────┼────────────────┨ ┃ ARTIFACT_STORE │ default ┃ ┠────────────────┼────────────────┨ ┃ ORCHESTRATOR │ default ┃ ┗━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛ 'default' stack (ACTIVE) Stack 'default' with id '...' is owned by user default and is 'private'. ... ``` `zenml stack list` lets you see all stacks that are registered in your zenml deployment. ```bash ... ┏━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓ ┃ ACTIVE │ STACK NAME │ STACK ID │ SHARED │ OWNER │ ARTIFACT_STORE │ ORCHESTRATOR ┃ ┠────────┼────────────┼───────────┼────────┼─────────┼────────────────┼──────────────┨ ┃ 👉 │ default │ ... │ ➖ │ default │ default │ default ┃ ┗━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛ ... ``` {% hint style="info" %} As you can see a stack can be **active** on your **client**. This simply means that any pipeline you run will be using the **active stack** as its environment. {% endhint %} ## Components of a stack As you can see in the section above, a stack consists of multiple components. All stacks have at minimum an **orchestrator** and an **artifact store**. ### Orchestrator The **orchestrator** is responsible for executing the pipeline code. In the simplest case, this will be a simple Python thread on your machine. Let's explore this default orchestrator. `zenml orchestrator list` lets you see all orchestrators that are registered in your zenml deployment. ```bash ┏━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┓ ┃ ACTIVE │ NAME │ COMPONENT ID │ FLAVOR │ SHARED │ OWNER ┃ ┠────────┼─────────┼──────────────┼────────┼────────┼─────────┨ ┃ 👉 │ default │ ... │ local │ ➖ │ default ┃ ┗━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┛ ``` ### Artifact store The **artifact store** is responsible for persisting the step outputs. As we learned in the previous section, the step outputs are not passed along in memory, rather the outputs of each step are stored in the **artifact store** and then loaded from there when the next step needs them. By default this will also be on your own machine: `zenml artifact-store list` lets you see all artifact stores that are registered in your zenml deployment. ```bash ┏━━━━━━━━┯━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━┯━━━━━━━━┯━━━━━━━━━┓ ┃ ACTIVE │ NAME │ COMPONENT ID │ FLAVOR │ SHARED │ OWNER ┃ ┠────────┼─────────┼──────────────┼────────┼────────┼─────────┨ ┃ 👉 │ default │ ... │ local │ ➖ │ default ┃ ┗━━━━━━━━┷━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━┷━━━━━━━━┷━━━━━━━━━┛ ``` ### Other stack components There are many more components that you can add to your stacks, like experiment trackers, model deployers, and more. You can see all supported stack component types in a single table view [here](../../component-guide/README.md) Perhaps the most important stack component after the orchestrator and the artifact store is the [container registry](../../component-guide/container-registries/container-registries.md). A container registry stores all your containerized images, which hold all your code and the environment needed to execute them. We will learn more about them in the next section! ## Registering a stack Just to illustrate how to interact with stacks, let's create an alternate local stack. We start by first creating a local artifact store. ### Create an artifact store ```bash zenml artifact-store register my_artifact_store --flavor=local ``` Let's understand the individual parts of this command: * `artifact-store` : This describes the top-level group, to find other stack components simply run `zenml --help` * `register` : Here we want to register a new component, instead, we could also `update` , `delete` and more `zenml artifact-store --help` will give you all possibilities * `my_artifact_store` : This is the unique name that the stack component will have. * `--flavor=local`: A flavor is a possible implementation for a stack component. So in the case of an artifact store, this could be an s3-bucket or a local filesystem. You can find out all possibilities with `zenml artifact-store flavor --list` This will be the output that you can expect from the command above. ```bash Using the default local database. Running with active stack: 'default' (global) Successfully registered artifact_store `my_artifact_store`.bash ``` To see the new artifact store that you just registered, just run: ```bash zenml artifact-store describe my_artifact_store ``` ### Create a local stack With the artifact store created, we can now create a new stack with this artifact store. ```bash zenml stack register a_new_local_stack -o default -a my_artifact_store ``` * `stack` : This is the CLI group that enables interactions with the stacks * `register`: Here we want to register a new stack. Explore other operations with`zenml stack --help`. * `a_new_local_stack` : This is the unique name that the stack will have. * `--orchestrator` or `-o` are used to specify which orchestrator to use for the stack * `--artifact-store` or `-a` are used to specify which artifact store to use for the stack The output for the command should look something like this: ```bash Using the default local database. Stack 'a_new_local_stack' successfully registered! ``` You can inspect the stack with the following command: ```bash zenml stack describe a_new_local_stack ``` Which will give you an output like this: ```bash Stack Configuration ┏━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━┓ ┃ COMPONENT_TYPE │ COMPONENT_NAME ┃ ┠────────────────┼───────────────────┨ ┃ ORCHESTRATOR │ default ┃ ┠────────────────┼───────────────────┨ ┃ ARTIFACT_STORE │ my_artifact_store ┃ ┗━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━┛ 'a_new_local_stack' stack Stack 'a_new_local_stack' with id '...' is owned by user default and is 'private'. ``` ### Switch stacks with our VS Code extension ![GIF of our VS code extension, showing some of the uses of the sidebar](../../.gitbook/assets/zenml-extension-shortened.gif) If you are using [our VS Code extension](https://marketplace.visualstudio.com/items?itemName=ZenML.zenml-vscode), you can easily view and switch your stacks by opening the sidebar (click on the ZenML icon). You can then click on the stack you want to switch to as well as view the stack components it's made up of. ### Run a pipeline on the new local stack Let's use the pipeline in our starter project from the [previous guide](../starter-guide/starter-project.md) to see it in action. If you have not already, clone the starter template: ```bash pip install "zenml[templates,server]" notebook zenml integration install sklearn -y mkdir zenml_starter cd zenml_starter zenml init --template starter --template-with-defaults # Just in case, we install the requirements again pip install -r requirements.txt ```
Above doesn't work? Here is an alternative The starter template is the same as the [ZenML mlops starter example](https://github.com/zenml-io/zenml/tree/main/examples/mlops_starter). You can clone it like so: ```bash git clone --depth 1 git@github.com:zenml-io/zenml.git cd zenml/examples/mlops_starter pip install -r requirements.txt zenml init ```
To run a pipeline using the new stack: 1. Set the stack as active on your client ```bash zenml stack set a_new_local_stack ``` 2. Run your pipeline code: ```bash python run.py --training-pipeline ``` Keep this code handy as we'll be using it in the next chapters!
ZenML Scarf
================ File: docs/book/user-guide/starter-guide/cache-previous-executions.md ================ --- description: Iterating quickly with ZenML through caching. --- # Cache previous executions Developing machine learning pipelines is iterative in nature. ZenML speeds up development in this work with step caching. In the logs of your previous runs, you might have noticed at this point that rerunning the pipeline a second time will use caching on the first step: ```bash Step training_data_loader has started. Using cached version of training_data_loader. Step svc_trainer has started. Train accuracy: 0.3416666666666667 Step svc_trainer has finished in 0.932s. ``` ![DAG of a cached pipeline run](../../.gitbook/assets/CachedDag.png) ZenML understands that nothing has changed between subsequent runs, so it re-uses the output of the previous run (the outputs are persisted in the [artifact store](../../component-guide/artifact-stores/artifact-stores.md)). This behavior is known as **caching**. In ZenML, caching is enabled by default. Since ZenML automatically tracks and versions all inputs, outputs, and parameters of steps and pipelines, steps will not be re-executed within the **same pipeline** on subsequent pipeline runs as long as there is **no change** in the inputs, parameters, or code of a step. If you run a pipeline without a schedule, ZenML will be able to compute the cached steps on your client machine. This means that these steps don't have to be executed by your [orchestrator](../../component-guide/orchestrators/orchestrators.md), which can save time and money when you're executing your pipelines remotely. If you always want your orchestrator to compute cached steps dynamically, you can set the `ZENML_PREVENT_CLIENT_SIDE_CACHING` environment variable to `True`. {% hint style="warning" %} The caching does not automatically detect changes within the file system or on external APIs. Make sure to **manually** set caching to `False` on steps that depend on **external inputs, file-system changes,** or if the step should run regardless of caching. ```python @step(enable_cache=False) def load_data_from_external_system(...) -> ...: # This step will always be run ``` {% endhint %} ## Configuring the caching behavior of your pipelines With caching as the default behavior, there will be times when you need to disable it. There are levels at which you can take control of when and where caching is used. ```mermaid graph LR A["Pipeline Settings"] -->|overwritten by| B["Step Settings"] B["Step Settings"] -->|overwritten by| C["Changes in Code, Inputs or Parameters"] ``` ### Caching at the pipeline level On a pipeline level, the caching policy can be set as a parameter within the `@pipeline` decorator as shown below: ```python @pipeline(enable_cache=False) def first_pipeline(....): """Pipeline with cache disabled""" ``` The setting above will disable caching for all steps in the pipeline unless a step explicitly sets `enable_cache=True` ( see below). {% hint style="info" %} When writing your pipelines, be explicit. This makes it clear when looking at the code if caching is enabled or disabled for any given pipeline. {% endhint %} #### Dynamically configuring caching for a pipeline run Sometimes you want to have control over caching at runtime instead of defaulting to the hard-coded pipeline and step decorator settings. ZenML offers a way to override all caching settings at runtime: ```python first_pipeline = first_pipeline.with_options(enable_cache=False) ``` The code above disables caching for all steps of your pipeline, no matter what you have configured in the `@step` or `@pipeline` decorators. The `with_options` function allows you to configure all sorts of things this way. We will learn more about it in the [coming chapters](../production-guide/configure-pipeline.md)! ### Caching at a step-level Caching can also be explicitly configured at a step level via a parameter of the `@step` decorator: ```python @step(enable_cache=False) def import_data_from_api(...): """Import most up-to-date data from public api""" ... ``` The code above turns caching off for this step only. You can also use `with_options` with the step, just as in the pipeline: ```python import_data_from_api = import_data_from_api.with_options(enable_cache=False) # use in your pipeline directly ``` ## Code Example This section combines all the code from this section into one simple script that you can use to see caching easily:
Code Example of this Section ```python from typing_extensions import Tuple, Annotated import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.base import ClassifierMixin from sklearn.svm import SVC from zenml import pipeline, step from zenml.logger import get_logger logger = get_logger(__name__) @step def training_data_loader() -> Tuple[ Annotated[pd.DataFrame, "X_train"], Annotated[pd.DataFrame, "X_test"], Annotated[pd.Series, "y_train"], Annotated[pd.Series, "y_test"], ]: """Load the iris dataset as tuple of Pandas DataFrame / Series.""" iris = load_iris(as_frame=True) X_train, X_test, y_train, y_test = train_test_split( iris.data, iris.target, test_size=0.2, shuffle=True, random_state=42 ) return X_train, X_test, y_train, y_test @step def svc_trainer( X_train: pd.DataFrame, y_train: pd.Series, gamma: float = 0.001, ) -> Tuple[ Annotated[ClassifierMixin, "trained_model"], Annotated[float, "training_acc"], ]: """Train a sklearn SVC classifier and log to MLflow.""" model = SVC(gamma=gamma) model.fit(X_train.to_numpy(), y_train.to_numpy()) train_acc = model.score(X_train.to_numpy(), y_train.to_numpy()) print(f"Train accuracy: {train_acc}") return model, train_acc @pipeline def training_pipeline(gamma: float = 0.002): X_train, X_test, y_train, y_test = training_data_loader() svc_trainer(gamma=gamma, X_train=X_train, y_train=y_train) if __name__ == "__main__": training_pipeline() # Step one will use cache, step two will rerun. # ZenML will detect a different value for the # `gamma` input of the second step and disable caching. logger.info("\n\nFirst step cached, second not due to parameter change") training_pipeline(gamma=0.0001) # This will disable cache for the second step. logger.info("\n\nFirst step cached, second not due to settings") svc_trainer = svc_trainer.with_options(enable_cache=False) training_pipeline() # This will disable cache for all steps. logger.info("\n\nCaching disabled for the entire pipeline") training_pipeline.with_options(enable_cache=False)() ```
ZenML Scarf
================ File: docs/book/user-guide/starter-guide/create-an-ml-pipeline.md ================ --- description: Start with the basics of steps and pipelines. --- # Create an ML pipeline In the quest for production-ready ML models, workflows can quickly become complex. Decoupling and standardizing stages such as data ingestion, preprocessing, and model evaluation allows for more manageable, reusable, and scalable processes. ZenML pipelines facilitate this by enabling each stage—represented as **Steps**—to be modularly developed and then integrated smoothly into an end-to-end **Pipeline**. Leveraging ZenML, you can create and manage robust, scalable machine learning (ML) pipelines. Whether for data preparation, model training, or deploying predictions, ZenML standardizes and streamlines the process, ensuring reproducibility and efficiency.

ZenML pipelines are simple Python code

{% hint style="info" %} Before starting this guide, make sure you have [installed ZenML](../../getting-started/installation.md): ```shell pip install "zenml[server]" zenml login --local # Will launch the dashboard locally ``` {% endhint %} ## Start with a simple ML pipeline Let's jump into an example that demonstrates how a simple pipeline can be set up in ZenML, featuring actual ML components to give you a better sense of its application. ```python from zenml import pipeline, step @step def load_data() -> dict: """Simulates loading of training data and labels.""" training_data = [[1, 2], [3, 4], [5, 6]] labels = [0, 1, 0] return {'features': training_data, 'labels': labels} @step def train_model(data: dict) -> None: """ A mock 'training' process that also demonstrates using the input data. In a real-world scenario, this would be replaced with actual model fitting logic. """ total_features = sum(map(sum, data['features'])) total_labels = sum(data['labels']) print(f"Trained model using {len(data['features'])} data points. " f"Feature sum is {total_features}, label sum is {total_labels}") @pipeline def simple_ml_pipeline(): """Define a pipeline that connects the steps.""" dataset = load_data() train_model(dataset) if __name__ == "__main__": run = simple_ml_pipeline() # You can now use the `run` object to see steps, outputs, etc. ``` {% hint style="info" %} * **`@step`** is a decorator that converts its function into a step that can be used within a pipeline * **`@pipeline`** defines a function as a pipeline and within this function, the steps are called and their outputs link them together. {% endhint %} Copy this code into a new file and name it `run.py`. Then run it with your command line: {% code overflow="wrap" %} ```bash $ python run.py Initiating a new run for the pipeline: simple_ml_pipeline. Executing a new run. Using user: hamza@zenml.io Using stack: default orchestrator: default artifact_store: default Step load_data has started. Step load_data has finished in 0.385s. Step train_model has started. Trained model using 3 data points. Feature sum is 21, label sum is 1 Step train_model has finished in 0.265s. Run simple_ml_pipeline-2023_11_23-10_51_59_657489 has finished in 1.612s. Pipeline visualization can be seen in the ZenML Dashboard. Run zenml login --local to see your pipeline! ``` {% endcode %} ### Explore the dashboard Once the pipeline has finished its execution, use the `zenml login --local` command to view the results in the ZenML Dashboard. Using that command will open up the browser automatically.

Landing Page of the Dashboard

Usually, the dashboard is accessible at [http://127.0.0.1:8237/](http://127.0.0.1:8237/). Log in with the default username **"default"** (password not required) and see your recently run pipeline. Browse through the pipeline components, such as the execution history and artifacts produced by your steps. Use the DAG visualization to understand the flow of data and to ensure all steps are completed successfully.

Diagram view of the run, with the runtime attributes of step 2.

For further insights, explore the logging and artifact information associated with each step, which can reveal details about the data and intermediate results. If you have closed the browser tab with the ZenML dashboard, you can always reopen it by running `zenml show` in your terminal. ## Understanding steps and artifacts When you ran the pipeline, each individual function that ran is shown in the DAG visualization as a `step` and is marked with the function name. Steps are connected with `artifacts`, which are simply the objects that are returned by these functions and input into downstream functions. This simple logic lets us break down our entire machine learning code into a sequence of tasks that pass data between each other. The artifacts produced by your steps are automatically stored and versioned by ZenML. The code that produced these artifacts is also automatically tracked. The parameters and all other configuration is also automatically captured. So you can see, by simply structuring your code within some functions and adding some decorators, we are one step closer to having a more tracked and reproducible codebase! ## Expanding to a Full Machine Learning Workflow With the fundamentals in hand, let’s escalate our simple pipeline to a complete ML workflow. For this task, we will use the well-known Iris dataset to train a Support Vector Classifier (SVC). Let's start with the imports. ```python from typing_extensions import Annotated # or `from typing import Annotated on Python 3.9+ from typing import Tuple import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.base import ClassifierMixin from sklearn.svm import SVC from zenml import pipeline, step ``` Make sure to install the requirements as well: ```bash pip install matplotlib zenml integration install sklearn -y ``` In this case, ZenML has an integration with `sklearn` so you can use the ZenML CLI to install the right version directly. {% hint style="info" %} The `zenml integration install sklearn` command is simply doing a `pip install` of `sklearn` behind the scenes. If something goes wrong, one can always use `zenml integration requirements sklearn` to see which requirements are compatible and install using pip (or any other tool) directly. (If no specific requirements are mentioned for an integration then this means we support using all possible versions of that integration/package.) {% endhint %} ### Define a data loader with multiple outputs A typical start of an ML pipeline is usually loading data from some source. This step will sometimes have multiple outputs. To define such a step, use a `Tuple` type annotation. Additionally, you can use the `Annotated` annotation to assign [custom output names](manage-artifacts.md#giving-names-to-your-artifacts). Here we load an open-source dataset and split it into a train and a test dataset. ```python import logging @step def training_data_loader() -> Tuple[ # Notice we use a Tuple and Annotated to return # multiple named outputs Annotated[pd.DataFrame, "X_train"], Annotated[pd.DataFrame, "X_test"], Annotated[pd.Series, "y_train"], Annotated[pd.Series, "y_test"], ]: """Load the iris dataset as a tuple of Pandas DataFrame / Series.""" logging.info("Loading iris...") iris = load_iris(as_frame=True) logging.info("Splitting train and test...") X_train, X_test, y_train, y_test = train_test_split( iris.data, iris.target, test_size=0.2, shuffle=True, random_state=42 ) return X_train, X_test, y_train, y_test ``` {% hint style="info" %} ZenML records the root python logging handler's output into the artifact store as a side-effect of running a step. Therefore, when writing steps, use the `logging` module to record logs, to ensure that these logs then show up in the ZenML dashboard. {% endhint %} ### Create a parameterized training step Here we are creating a training step for a support vector machine classifier with `sklearn`. As we might want to adjust the hyperparameter `gamma` later on, we define it as an input value to the step as well. ```python @step def svc_trainer( X_train: pd.DataFrame, y_train: pd.Series, gamma: float = 0.001, ) -> Tuple[ Annotated[ClassifierMixin, "trained_model"], Annotated[float, "training_acc"], ]: """Train a sklearn SVC classifier.""" model = SVC(gamma=gamma) model.fit(X_train.to_numpy(), y_train.to_numpy()) train_acc = model.score(X_train.to_numpy(), y_train.to_numpy()) print(f"Train accuracy: {train_acc}") return model, train_acc ``` {% hint style="info" %} If you want to run just a single step on your ZenML stack, all you need to do is call the step function outside of a ZenML pipeline. For example: ```python model, train_acc = svc_trainer(X_train=..., y_train=...) ``` {% endhint %} Next, we will combine our two steps into a pipeline and run it. As you can see, the parameter gamma is configurable as a pipeline input as well. ```python @pipeline def training_pipeline(gamma: float = 0.002): X_train, X_test, y_train, y_test = training_data_loader() svc_trainer(gamma=gamma, X_train=X_train, y_train=y_train) if __name__ == "__main__": training_pipeline(gamma=0.0015) ``` {% hint style="info" %} Best Practice: Always nest the actual execution of the pipeline inside an `if __name__ == "__main__"` condition. This ensures that loading the pipeline from elsewhere does not also run it. ```python if __name__ == "__main__": training_pipeline() ``` {% endhint %} Running `python run.py` should look somewhat like this in the terminal:
Registered new pipeline with name `training_pipeline`.
.
.
.
Pipeline run `training_pipeline-2023_04_29-09_19_54_273710` has finished in 0.236s.
In the dashboard, you should now be able to see this new run, along with its runtime configuration and a visualization of the training data.

Run created by the code in this section along with a visualization of the ground-truth distribution.

### Configure with a YAML file Instead of configuring your pipeline runs in code, you can also do so from a YAML file. This is best when we do not want to make unnecessary changes to the code; in production this is usually the case. To do this, simply reference the file like this: ```python # Configure the pipeline training_pipeline = training_pipeline.with_options( config_path='/local/path/to/config.yaml' ) # Run the pipeline training_pipeline() ``` The reference to a local file will change depending on where you are executing the pipeline and code from, so please bear this in mind. It is best practice to put all config files in a configs directory at the root of your repository and check them into git history. A simple version of such a YAML file could be: ```yaml parameters: gamma: 0.01 ``` Please note that this would take precedence over any parameters passed in the code. If you are unsure how to format this config file, you can generate a template config file from a pipeline. ```python training_pipeline.write_run_configuration_template(path='/local/path/to/config.yaml') ``` Check out [this section](../../how-to/pipeline-development/use-configuration-files/README.md) for advanced configuration options. ## 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 typing_extensions import Tuple, Annotated import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.base import ClassifierMixin from sklearn.svm import SVC from zenml import pipeline, step @step def training_data_loader() -> Tuple[ Annotated[pd.DataFrame, "X_train"], Annotated[pd.DataFrame, "X_test"], Annotated[pd.Series, "y_train"], Annotated[pd.Series, "y_test"], ]: """Load the iris dataset as tuple of Pandas DataFrame / Series.""" iris = load_iris(as_frame=True) X_train, X_test, y_train, y_test = train_test_split( iris.data, iris.target, test_size=0.2, shuffle=True, random_state=42 ) return X_train, X_test, y_train, y_test @step def svc_trainer( X_train: pd.DataFrame, y_train: pd.Series, gamma: float = 0.001, ) -> Tuple[ Annotated[ClassifierMixin, "trained_model"], Annotated[float, "training_acc"], ]: """Train a sklearn SVC classifier and log to MLflow.""" model = SVC(gamma=gamma) model.fit(X_train.to_numpy(), y_train.to_numpy()) train_acc = model.score(X_train.to_numpy(), y_train.to_numpy()) print(f"Train accuracy: {train_acc}") return model, train_acc @pipeline def training_pipeline(gamma: float = 0.002): X_train, X_test, y_train, y_test = training_data_loader() svc_trainer(gamma=gamma, X_train=X_train, y_train=y_train) if __name__ == "__main__": training_pipeline() ```
ZenML Scarf
================ File: docs/book/user-guide/starter-guide/manage-artifacts.md ================ --- description: Understand and adjust how ZenML versions your data. --- # Manage artifacts Data sits at the heart of every machine learning workflow. Managing and versioning this data correctly is essential for reproducibility and traceability within your ML pipelines. ZenML takes a proactive approach to data versioning, ensuring that every artifact—be it data, models, or evaluations—is automatically tracked and versioned upon pipeline execution. ![Walkthrough of ZenML Artifact Control Plane (Dashboard available only on ZenML Pro)](../../.gitbook/assets/dcp\_walkthrough.gif) This guide will delve into artifact versioning and management, showing you how to efficiently name, organize, and utilize your data with the ZenML framework. ## Managing artifacts produced by ZenML pipelines Artifacts, the outputs of your steps and pipelines, are automatically versioned and stored in the artifact store. Configuring these artifacts is pivotal for transparent and efficient pipeline development. ### Giving names to your artifacts Assigning custom names to your artifacts can greatly enhance their discoverability and manageability. As best practice, utilize the `Annotated` object within your steps to give precise, human-readable names to outputs: ```python from typing_extensions import Annotated import pandas as pd from sklearn.datasets import load_iris from zenml import pipeline, step # Using Annotated to name our dataset @step def training_data_loader() -> Annotated[pd.DataFrame, "iris_dataset"]: """Load the iris dataset as pandas dataframe.""" iris = load_iris(as_frame=True) return iris.get("frame") @pipeline def feature_engineering_pipeline(): training_data_loader() if __name__ == "__main__": feature_engineering_pipeline() ``` {% hint style="info" %} Unspecified artifact outputs default to a naming pattern of `{pipeline_name}::{step_name}::output`. For visual exploration in the ZenML dashboard, it's best practice to give significant outputs clear custom names. {% endhint %} Artifacts named `iris_dataset` can then be found swiftly using various ZenML interfaces: {% tabs %} {% tab title="OSS (CLI)" %} To list artifacts: `zenml artifact list` {% endtab %} {% tab title="Cloud (Dashboard)" %} The [ZenML Pro](https://zenml.io/pro) dashboard offers advanced visualization features for artifact exploration.

ZenML Artifact Control Plane.

{% hint style="info" %} To prevent visual clutter, make sure to assign names to your most important artifacts that you would like to explore visually. {% endhint %} {% endtab %} {% endtabs %} ### Versioning artifacts manually ZenML automatically versions all created artifacts using auto-incremented numbering. I.e., if you have defined a step creating an artifact named `iris_dataset` as shown above, the first execution of the step will create an artifact with this name and version "1", the second execution will create version "2", and so on. While ZenML handles artifact versioning automatically, you have the option to specify custom versions using the [`ArtifactConfig`](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-model/#zenml.model.artifact\_config.DataArtifactConfig). This may come into play during critical runs like production releases. ```python from zenml import step, ArtifactConfig @step def training_data_loader() -> ( Annotated[ pd.DataFrame, # Add `ArtifactConfig` to control more properties of your artifact ArtifactConfig( name="iris_dataset", version="raw_2023" ), ] ): ... ``` The next execution of this step will then create an artifact with the name `iris_dataset` and version `raw_2023`. This is primarily useful if you are making a particularly important pipeline run (such as a release) whose artifacts you want to distinguish at a glance later. {% hint style="warning" %} Since custom versions cannot be duplicated, the above step can only be run once successfully. To avoid altering your code frequently, consider using a [YAML config](../production-guide/configure-pipeline.md) for artifact versioning. {% endhint %} After execution, `iris_dataset` and its version `raw_2023` can be seen using: {% tabs %} {% tab title="OSS (CLI)" %} To list versions: `zenml artifact version list` {% endtab %} {% tab title="Cloud (Dashboard)" %} The Cloud dashboard visualizes version history for your review.

ZenML Data Versions List.

{% endtab %} {% endtabs %} ### Add metadata and tags to artifacts If you would like to extend your artifacts with extra metadata or tags you can do so by following the patterns demonstrated below: ```python from zenml import step, get_step_context, ArtifactConfig from typing_extensions import Annotated # below we annotate output with `ArtifactConfig` giving it a name, # run_metadata and tags. As a result, the created artifact # `artifact_name` will get configured with metadata and tags @step def annotation_approach() -> ( Annotated[ str, ArtifactConfig( name="artifact_name", run_metadata={"metadata_key": "metadata_value"}, tags=["tag_name"], ), ] ): return "string" # below we annotate output using functional approach with # run_metadata and tags. As a result, the created artifact # `artifact_name` will get configured with metadata and tags @step def annotation_approach() -> Annotated[str, "artifact_name"]: step_context = get_step_context() step_context.add_output_metadata( output_name="artifact_name", metadata={"metadata_key": "metadata_value"} ) step_context.add_output_tags(output_name="artifact_name", tags=["tag_name"]) return "string" # below we combine both approaches, so the artifact will get # metadata and tags from both sources @step def annotation_approach() -> ( Annotated[ str, ArtifactConfig( name="artifact_name", run_metadata={"metadata_key": "metadata_value"}, tags=["tag_name"], ), ] ): step_context = get_step_context() step_context.add_output_metadata( output_name="artifact_name", metadata={"metadata_key2": "metadata_value2"} ) step_context.add_output_tags(output_name="artifact_name", tags=["tag_name2"]) return "string" ``` ## Comparing metadata across runs (Pro) The [ZenML Pro](https://www.zenml.io/pro) dashboard includes an Experiment Comparison tool that allows you to visualize and analyze metadata across different pipeline runs. This feature helps you understand patterns and changes in your pipeline's behavior over time. ### Using the comparison views The tool offers two complementary views for analyzing your metadata: #### Table View The tabular view provides a structured comparison of metadata across runs: ![Comparing metadata values across different pipeline runs in table view.](../../../book/.gitbook/assets/table-view.png) This view automatically calculates changes between runs and allows you to: * Sort and filter metadata values * Track changes over time * Compare up to 20 runs simultaneously #### Parallel Coordinates View The parallel coordinates visualization helps identify relationships between different metadata parameters: ![Comparing metadata values across different pipeline runs in parallel coordinates view.](../../../book/.gitbook/assets/coordinates-view.png) This view is particularly useful for: * Discovering correlations between different metrics * Identifying patterns across pipeline runs * Filtering and focusing on specific parameter ranges ### Accessing the comparison tool To compare metadata across runs: 1. Navigate to any pipeline in your dashboard 2. Click the "Compare" button in the top navigation 3. Select the runs you want to compare 4. Switch between table and parallel coordinates views using the tabs {% hint style="info" %} The comparison tool works with any numerical metadata (`float` or `int`) that you've logged in your pipelines. Make sure to log meaningful metrics in your steps to make the most of this feature. {% endhint %} ### Sharing comparisons The tool preserves your comparison configuration in the URL, making it easy to share specific views with team members. Simply copy and share the URL to allow others to see the same comparison with identical settings and filters. {% hint style="warning" %} This feature is currently in Alpha Preview. We encourage you to share feedback about your use cases and requirements through our Slack community. {% endhint %} ## Specify a type for your artifacts Assigning a type to an artifact allows ZenML to highlight them differently in the dashboard and also lets you filter your artifacts better. {% hint style="info" %} If you don't specify a type for your artifact, ZenML will use the default artifact type provided by the materializer that is used to save the artifact. {% endhint %} ```python from typing_extensions import Annotated from zenml import ArtifactConfig, save_artifact, step from zenml.enums import ArtifactType # Assign an artifact type to a step output @step def trainer() -> Annotated[MyCustomModel, ArtifactConfig(artifact_type=ArtifactType.MODEL)]: return MyCustomModel(...) # Assign an artifact type when manually saving artifacts model = ... save_artifact(model, name="model", artifact_type=ArtifactType.MODEL) ``` ## Consuming external artifacts within a pipeline While most pipelines start with a step that produces an artifact, it is often the case to want to consume artifacts external from the pipeline. The `ExternalArtifact` class can be used to initialize an artifact within ZenML with any arbitrary data type. For example, let's say we have a Snowflake query that produces a dataframe, or a CSV file that we need to read. External artifacts can be used for this, to pass values to steps that are neither JSON serializable nor produced by an upstream step: ```python import numpy as np from zenml import ExternalArtifact, pipeline, step @step def print_data(data: np.ndarray): print(data) @pipeline def printing_pipeline(): # One can also pass data directly into the ExternalArtifact # to create a new artifact on the fly data = ExternalArtifact(value=np.array([0])) print_data(data=data) if __name__ == "__main__": printing_pipeline() ``` Optionally, you can configure the `ExternalArtifact` to use a custom [materializer](../../how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md) for your data or disable artifact metadata and visualizations. Check out the [SDK docs](https://sdkdocs.zenml.io/latest/core\_code\_docs/core-artifacts/#zenml.artifacts.external\_artifact.ExternalArtifact) for all available options. {% hint style="info" %} Using an `ExternalArtifact` for your step automatically disables caching for the step. {% endhint %} ## Consuming artifacts produced by other pipelines It is also common to consume an artifact downstream after producing it in an upstream pipeline or step. As we have learned in the [previous section](../../how-to/pipeline-development/build-pipelines/fetching-pipelines.md#fetching-artifacts-directly), the `Client` can be used to fetch artifacts directly inside the pipeline code: ```python from uuid import UUID import pandas as pd from zenml import step, pipeline from zenml.client import Client @step def trainer(dataset: pd.DataFrame): ... @pipeline def training_pipeline(): client = Client() # Fetch by ID dataset_artifact = client.get_artifact_version( name_id_or_prefix=UUID("3a92ae32-a764-4420-98ba-07da8f742b76") ) # Fetch by name alone - uses the latest version of this artifact dataset_artifact = client.get_artifact_version(name_id_or_prefix="iris_dataset") # Fetch by name and version dataset_artifact = client.get_artifact_version( name_id_or_prefix="iris_dataset", version="raw_2023" ) # Pass into any step trainer(dataset=dataset_artifact) if __name__ == "__main__": training_pipeline() ``` {% hint style="info" %} Calls of `Client` methods like `get_artifact_version` directly inside the pipeline code makes use of ZenML's [late materialization](../../how-to/data-artifact-management/handle-data-artifacts/load-artifacts-into-memory.md) behind the scenes. {% endhint %} If you would like to bypass materialization entirely and just download the data or files associated with a particular artifact version, you can use the `.download_files` method: ```python from zenml.client import Client client = Client() artifact = client.get_artifact_version(name_id_or_prefix="iris_dataset") artifact.download_files("path/to/save.zip") ``` Take note that the path must have the `.zip` extension, as the artifact data will be saved as a zip file. Make sure to handle any exceptions that may arise from this operation. ## Managing artifacts **not** produced by ZenML pipelines Sometimes, artifacts can be produced completely outside of ZenML. A good example of this is the predictions produced by a deployed model. ```python # A model is deployed, running in a FastAPI container # Let's use the ZenML client to fetch the latest model and make predictions from zenml.client import Client from zenml import save_artifact # Fetch the model from a registry or a previous pipeline model = ... # Let's make a prediction prediction = model.predict([[1, 1, 1, 1]]) # We now store this prediction in ZenML as an artifact # This will create a new artifact version save_artifact(prediction, name="iris_predictions") ``` You can also load any artifact stored within ZenML using the `load_artifact` method: ```python # Loads the latest version load_artifact("iris_predictions") ``` {% hint style="info" %} `load_artifact` is simply short-hand for the following Client call: ```python from zenml.client import Client client = Client() client.get_artifact("iris_predictions").load() ``` {% endhint %} Even if an artifact is created externally, it can be treated like any other artifact produced by ZenML steps - with all the functionalities described above! {% hint style="info" %} It is also possible to use these functions inside your ZenML steps. However, it is usually cleaner to return the artifacts as outputs of your step to save them, or to use External Artifacts to load them instead. {% endhint %} ### Linking existing data as a ZenML artifact Sometimes, data is produced completely outside of ZenML and can be conveniently stored on a given storage. A good example of this is the checkpoint files created as a side-effect of the Deep Learning model training. We know that the intermediate data of the deep learning frameworks is quite big and there is no good reason to move it around again and again, if it can be produced directly in the artifact store boundaries and later just linked to become an artifact of ZenML. Let's explore the Pytorch Lightning example to fit the model and store the checkpoints in a remote location. ```python import os from zenml.client import Client from zenml import register_artifact from pytorch_lightning import Trainer from pytorch_lightning.callbacks import ModelCheckpoint from uuid import uuid4 # Define where the model data should be saved # use active ArtifactStore prefix = Client().active_stack.artifact_store.path # keep data separable for future runs with uuid4 folder default_root_dir = os.path.join(prefix, uuid4().hex) # Define the model and fit it model = ... trainer = Trainer( default_root_dir=default_root_dir, callbacks=[ ModelCheckpoint( every_n_epochs=1, save_top_k=-1, filename="checkpoint-{epoch:02d}" ) ], ) try: trainer.fit(model) finally: # We now link those checkpoints in ZenML as an artifact # This will create a new artifact version register_artifact(default_root_dir, name="all_my_model_checkpoints") ``` {% hint style="info" %} The artifact produced from the preexisting data will have a `pathlib.Path` type, once loaded or passed as input to another step. {% endhint %} Even if an artifact is created and stored externally, it can be treated like any other artifact produced by ZenML steps - with all the functionalities described above! For more details and use-cases check-out detailed docs page [Register Existing Data as a ZenML Artifact](../../how-to/data-artifact-management/complex-usecases/registering-existing-data.md). ## Logging metadata for an artifact One of the most useful ways of interacting with artifacts in ZenML is the ability to associate metadata with them. [As mentioned before](../../how-to/pipeline-development/build-pipelines/fetching-pipelines.md#artifact-information), artifact metadata is an arbitrary dictionary of key-value pairs that are useful for understanding the nature of the data. As an example, one can associate the results of a model training alongside a model artifact, the shape of a table alongside a `pandas` dataframe, or the size of an image alongside a PNG file. For some artifacts, ZenML automatically logs metadata. As an example, for `pandas.Series` and `pandas.DataFrame` objects, ZenML logs the shape and size of the objects: {% tabs %} {% tab title="Python" %} ```python from zenml.client import Client # Get an artifact version (e.g. pd.DataFrame) artifact = Client().get_artifact_version('50ce903f-faa6-41f6-a95f-ff8c0ec66010') # Fetch it's metadata artifact.run_metadata["storage_size"].value # Size in bytes artifact.run_metadata["shape"].value # Shape e.g. (500,20) ``` {% endtab %} {% tab title="OSS (Dashboard)" %} The information regarding the metadata of an artifact can be found within the DAG visualizer interface on the OSS dashboard:

ZenML Artifact Control Plane.

{% endtab %} {% tab title="Cloud (Dashboard)" %} The [ZenML Pro](https://zenml.io/pro) dashboard offers advanced visualization features for artifact exploration, including a dedicated artifacts tab with metadata visualization:

ZenML Artifact Control Plane.

{% endtab %} {% endtabs %} A user can also add metadata to an artifact within a step directly using the `log_artifact_metadata` method: ```python from zenml import step, log_artifact_metadata @step def model_finetuner_step( model: ClassifierMixin, dataset: Tuple[np.ndarray, np.ndarray] ) -> Annotated[ ClassifierMixin, ArtifactConfig(name="my_model", tags=["SVC", "trained"]) ]: """Finetunes a given model on a given dataset.""" model.fit(dataset[0], dataset[1]) accuracy = model.score(dataset[0], dataset[1]) log_artifact_metadata( # Artifact name can be omitted if step returns only one output artifact_name="my_model", # Passing None or omitting this will use the `latest` version version=None, # Metadata should be a dictionary of JSON-serializable values metadata={"accuracy": float(accuracy)} # A dictionary of dictionaries can also be passed to group metadata # in the dashboard # metadata = {"metrics": {"accuracy": accuracy}} ) return model ``` For further depth, there is an [advanced metadata logging guide](../../how-to/model-management-metrics/track-metrics-metadata/README.md) that goes more into detail about logging metadata in ZenML. Additionally, there is a lot more to learn about artifacts within ZenML. Please read the [dedicated data management guide](../../how-to/handle-data-artifacts/) for more information. ## Code example This section combines all the code from this section into one simple script that you can use easily:
Code Example of this Section ```python from typing import Optional, Tuple from typing_extensions import Annotated import numpy as np from sklearn.base import ClassifierMixin from sklearn.datasets import load_digits from sklearn.svm import SVC from zenml import ArtifactConfig, pipeline, step, log_artifact_metadata from zenml import save_artifact, load_artifact from zenml.client import Client @step def versioned_data_loader_step() -> ( Annotated[ Tuple[np.ndarray, np.ndarray], ArtifactConfig( name="my_dataset", tags=["digits", "computer vision", "classification"], ), ] ): """Loads the digits dataset as a tuple of flattened numpy arrays.""" digits = load_digits() return (digits.images.reshape((len(digits.images), -1)), digits.target) @step def model_finetuner_step( model: ClassifierMixin, dataset: Tuple[np.ndarray, np.ndarray] ) -> Annotated[ ClassifierMixin, ArtifactConfig(name="my_model", tags=["SVC", "trained"]), ]: """Finetunes a given model on a given dataset.""" model.fit(dataset[0], dataset[1]) accuracy = model.score(dataset[0], dataset[1]) log_artifact_metadata(metadata={"accuracy": float(accuracy)}) return model @pipeline def model_finetuning_pipeline( dataset_version: Optional[str] = None, model_version: Optional[str] = None, ): client = Client() # Either load a previous version of "my_dataset" or create a new one if dataset_version: dataset = client.get_artifact_version( name_id_or_prefix="my_dataset", version=dataset_version ) else: dataset = versioned_data_loader_step() # Load the model to finetune # If no version is specified, the latest version of "my_model" is used model = client.get_artifact_version( name_id_or_prefix="my_model", version=model_version ) # Finetune the model # This automatically creates a new version of "my_model" model_finetuner_step(model=model, dataset=dataset) def main(): # Save an untrained model as first version of "my_model" untrained_model = SVC(gamma=0.001) save_artifact( untrained_model, name="my_model", version="1", tags=["SVC", "untrained"] ) # Create a first version of "my_dataset" and train the model on it model_finetuning_pipeline() # Finetune the latest model on an older version of the dataset model_finetuning_pipeline(dataset_version="1") # Run inference with the latest model on an older version of the dataset latest_trained_model = load_artifact("my_model") old_dataset = load_artifact("my_dataset", version="1") latest_trained_model.predict(old_dataset[0]) if __name__ == "__main__": main() ``` This would create the following pipeline run DAGs: **Run 1:** Create a first version of my_dataset **Run 2:** Uses a second version of my_dataset
ZenML Scarf
================ File: docs/book/user-guide/starter-guide/README.md ================ --- icon: seedling description: Kickstart your journey into MLOps with the essentials of ZenML. --- # Starter guide Welcome to the ZenML Starter Guide! If you're an MLOps engineer aiming to build robust ML platforms, or a data scientist interested in leveraging the power of MLOps, this is the perfect place to begin. Our guide is designed to provide you with the foundational knowledge of the ZenML framework and equip you with the initial tools to manage the complexity of machine learning operations.

Embarking on MLOps can be intricate. ZenML simplifies the journey.

Throughout this guide, we'll cover essential topics including: * [Creating your first ML pipeline](create-an-ml-pipeline.md) * [Understanding caching between pipeline steps](cache-previous-executions.md) * [Managing data and data versioning](manage-artifacts.md) * [Tracking your machine learning models](track-ml-models.md) Before jumping in, make sure you have a Python environment ready and `virtualenv` installed to follow along with ease. By the end, you will have completed a [starter project](starter-project.md), marking the beginning of your journey into MLOps with ZenML. Let this guide be not only your introduction to ZenML but also a foundational asset in your MLOps toolkit. Prepare your development environment, and let's get started!
ZenML Scarf
================ File: docs/book/user-guide/starter-guide/starter-project.md ================ --- description: Put your new knowledge into action with a simple starter project --- # A starter project By now, you have understood some of the basic pillars of a MLOps system: * [Pipelines and steps](create-an-ml-pipeline.md) * [Artifacts](manage-artifacts.md) * [Models](track-ml-models.md) We will now put this into action with a simple starter project. ## Get started Start with a fresh virtual environment with no dependencies. Then let's install our dependencies: ```bash pip install "zenml[templates,server]" notebook zenml integration install sklearn -y ``` We will then use [ZenML templates](../../how-to/project-setup-and-management/collaborate-with-team/project-templates/README.md) to help us get the code we need for the project: ```bash mkdir zenml_starter cd zenml_starter zenml init --template starter --template-with-defaults # Just in case, we install the requirements again pip install -r requirements.txt ```
Above doesn't work? Here is an alternative The starter template is the same as the [ZenML mlops starter example](https://github.com/zenml-io/zenml/tree/main/examples/mlops_starter). You can clone it like so: ```bash git clone --depth 1 git@github.com:zenml-io/zenml.git cd zenml/examples/mlops_starter pip install -r requirements.txt zenml init ```
## What you'll learn You can either follow along in the [accompanying Jupyter notebook](https://github.com/zenml-io/zenml/blob/main/examples/quickstart/quickstart.ipynb), or just keep reading the [README file for more instructions](https://github.com/zenml-io/zenml/blob/main/examples/quickstart/README.md). Either way, at the end you would run three pipelines that are exemplary: * A feature engineering pipeline that loads data and prepares it for training. * A training pipeline that loads the preprocessed dataset and trains a model. * A batch inference pipeline that runs predictions on the trained model with new data. And voilà! You're now well on your way to be an MLOps expert. As a next step, try introducing the [ZenML starter template](https://github.com/zenml-io/template-starter) to your colleagues and see the benefits of a standard MLOps framework in action! ## Conclusion and next steps This marks the end of the first chapter of your MLOps journey with ZenML. Make sure you do your own experimentation with ZenML to master the basics. When ready, move on to the [production guide](../production-guide/), which is the next part of the series.
ZenML Scarf
================ File: docs/book/user-guide/starter-guide/track-ml-models.md ================ --- description: Creating a full picture of a ML model using the Model Control Plane --- # Track ML models ![Walkthrough of ZenML Model Control Plane (Dashboard available only on ZenML Pro)](../../.gitbook/assets/mcp_walkthrough.gif) As discussed in the [Core Concepts](../../getting-started/core-concepts.md), ZenML also contains the notion of a `Model`, which consists of many model versions (the iterations of the model). These concepts are exposed in the `Model Control Plane` (MCP for short). ## What is a ZenML Model? Before diving in, let's take some time to build an understanding of what we mean when we say `Model` in ZenML terms. A `Model` is simply an entity that groups pipelines, artifacts, metadata, and other crucial business data into a unified entity. In this sense, a ZenML Model is a concept that more broadly encapsulates your ML product's business logic. You may even think of a ZenML Model as a "project" or a "workspace" {% hint style="warning" %} Please note that one of the most common artifacts that is associated with a Model in ZenML is the so-called technical model, which is the actually model file/files that holds the weight and parameters of a machine learning training result. However, this is not the only artifact that is relevant; artifacts such as the training data and the predictions this model produces in production are also linked inside a ZenML Model. {% endhint %} Models are first-class citizens in ZenML and as such viewing and using them is unified and centralized in the ZenML API, the ZenML client as well as on the [ZenML Pro](https://zenml.io/pro) dashboard. These models can be viewed within ZenML: {% tabs %} {% tab title="OSS (CLI)" %} `zenml model list` can be used to list all models. {% endtab %} {% tab title="Cloud (Dashboard)" %} The [ZenML Pro](https://zenml.io/pro) dashboard has additional capabilities, that include visualizing these models in the dashboard.

ZenML Model Control Plane.

{% endtab %} {% endtabs %} ## Configuring a model in a pipeline The easiest way to use a ZenML model is to pass a `Model` object as part of a pipeline run. This can be done easily at a pipeline or a step level, or via a [YAML config](../production-guide/configure-pipeline.md). Once you configure a pipeline this way, **all** artifacts generated during pipeline runs are automatically **linked** to the specified model. This connecting of artifacts provides lineage tracking and transparency into what data and models are used during training, evaluation, and inference. ```python from zenml import pipeline from zenml import Model model = Model( # The name uniquely identifies this model # It usually represents the business use case name="iris_classifier", # The version specifies the version # If None or an unseen version is specified, it will be created # Otherwise, a version will be fetched. version=None, # Some other properties may be specified license="Apache 2.0", description="A classification model for the iris dataset.", ) # The step configuration will take precedence over the pipeline @step(model=model) def svc_trainer(...) -> ...: ... # This configures it for all steps within the pipeline @pipeline(model=model) def training_pipeline(gamma: float = 0.002): # Now this pipeline will have the `iris_classifier` model active. X_train, X_test, y_train, y_test = training_data_loader() svc_trainer(gamma=gamma, X_train=X_train, y_train=y_train) if __name__ == "__main__": training_pipeline() # In the YAML the same can be done; in this case, the # passing to the decorators is not needed # model: # name: iris_classifier # license: "Apache 2.0" # description: "A classification model for the iris dataset." ``` The above will establish a **link between all artifacts that pass through this ZenML pipeline and this model**. This includes the **technical model** which is what comes out of the `svc_trainer` step. You will be able to see all associated artifacts and pipeline runs, all within one view. Furthermore, this pipeline run and all other pipeline runs that are configured with this model configuration will be linked to this model as well. You can see all versions of a model, and associated artifacts and run like this: {% tabs %} {% tab title="OSS (CLI)" %} `zenml model version list ` can be used to list all versions of a particular model. The following commands can be used to list the various pipeline runs associated with a model: * `zenml model version runs ` The following commands can be used to list the various artifacts associated with a model: * `zenml model version data_artifacts ` * `zenml model version model_artifacts ` * `zenml model version deployment_artifacts ` {% endtab %} {% tab title="Cloud (Dashboard)" %} The [ZenML Pro](https://zenml.io/pro) dashboard has additional capabilities, that include visualizing all associated runs and artifacts for a model version:
ZenML Model Versions List.

ZenML Model versions List.

{% endtab %} {% endtabs %} ## Fetching the model in a pipeline When configured at the pipeline or step level, the model will be available through the [StepContext](../../how-to/model-management-metrics/track-metrics-metadata/fetch-metadata-within-pipeline.md) or [PipelineContext](../../how-to/model-management-metrics/track-metrics-metadata/fetch-metadata-within-pipeline.md). ```python from zenml import get_step_context, get_pipeline_context, step, pipeline @step def svc_trainer( X_train: pd.DataFrame, y_train: pd.Series, gamma: float = 0.001, ) -> Annotated[ClassifierMixin, "trained_model"]: # This will return the model specified in the # @pipeline decorator. In this case, the production version of # the `iris_classifier` will be returned in this case. model = get_step_context().model ... @pipeline( model=Model( # The name uniquely identifies this model name="iris_classifier", # Pass the stage you want to get the right model version="production", ), ) def training_pipeline(gamma: float = 0.002): # Now this pipeline will have the production `iris_classifier` model active. model = get_pipeline_context().model X_train, X_test, y_train, y_test = training_data_loader() svc_trainer(gamma=gamma, X_train=X_train, y_train=y_train) ``` ## Logging metadata to the `Model` object [Just as one can associate metadata with artifacts](manage-artifacts.md#logging-metadata-for-an-artifact), models too can take a dictionary of key-value pairs to capture their metadata. This is achieved using the `log_model_metadata` method: ```python from zenml import get_step_context, step, log_model_metadata @step def svc_trainer( X_train: pd.DataFrame, y_train: pd.Series, gamma: float = 0.001, ) -> Annotated[ClassifierMixin, "sklearn_classifier"],: # Train and score model ... model.fit(dataset[0], dataset[1]) accuracy = model.score(dataset[0], dataset[1]) model = get_step_context().model log_model_metadata( # Model name can be omitted if specified in the step or pipeline context model_name="iris_classifier", # Passing None or omitting this will use the `latest` version version=None, # Metadata should be a dictionary of JSON-serializable values metadata={"accuracy": float(accuracy)} # A dictionary of dictionaries can also be passed to group metadata # in the dashboard # metadata = {"metrics": {"accuracy": accuracy}} ) ``` {% tabs %} {% tab title="Python" %} ```python from zenml.client import Client # Get an artifact version (in this the latest `iris_classifier`) model_version = Client().get_model_version('iris_classifier') # Fetch it's metadata model_version.run_metadata["accuracy"].value ``` {% endtab %} {% tab title="Cloud (Dashboard)" %} The [ZenML Pro](https://zenml.io/pro) dashboard offers advanced visualization features for artifact exploration, including a dedicated artifacts tab with metadata visualization:

ZenML Artifact Control Plane.

{% endtab %} {% endtabs %} Choosing [log metadata with artifacts](manage-artifacts.md#logging-metadata-for-an-artifact) or model versions depends on the scope and purpose of the information you wish to capture. Artifact metadata is best for details specific to individual outputs, while model version metadata is suitable for broader information relevant to the overall model. By utilizing ZenML's metadata logging capabilities and special types, you can enhance the traceability, reproducibility, and analysis of your ML workflows. Once metadata has been logged to a model, we can retrieve it easily with the client: ```python from zenml.client import Client client = Client() model = client.get_model_version("my_model", "my_version") print(model.run_metadata["metadata_key"].value) ``` For further depth, there is an [advanced metadata logging guide](../../how-to/model-management-metrics/track-metrics-metadata/README.md) that goes more into detail about logging metadata in ZenML. ## Using the stages of a model A model's versions can exist in various stages. These are meant to signify their lifecycle state: * `staging`: This version is staged for production. * `production`: This version is running in a production setting. * `latest`: The latest version of the model. * `archived`: This is archived and no longer relevant. This stage occurs when a model moves out of any other stage. {% tabs %} {% tab title="Python SDK" %} ```python from zenml import Model # Get the latest version of a model model = Model( name="iris_classifier", version="latest" ) # Get `my_version` version of a model model = Model( name="iris_classifier", version="my_version", ) # Pass the stage into the version field # to get the `staging` model model = Model( name="iris_classifier", version="staging", ) # This will set this version to production model.set_stage(stage="production", force=True) ``` {% endtab %} {% tab title="CLI" %} ```shell # List staging models zenml model version list --stage staging # Update to production zenml model version update -s production ``` {% endtab %} {% tab title="Cloud (Dashboard)" %} The [ZenML Pro](https://zenml.io/pro) dashboard has additional capabilities, that include easily changing the stage: ![ZenML Pro Transition Model Stages](../../.gitbook/assets/dcp\_transition\_stage.gif) {% endtab %} {% endtabs %} ZenML Model and versions are some of the most powerful features in ZenML. To understand them in a deeper way, read the [dedicated Model Management](../../how-to/model-management-metrics/model-control-plane/README.md) guide.
ZenML Scarf
================ File: docs/book/introduction.md ================ --- icon: torii-gate description: Welcome to ZenML! --- # Introduction **ZenML** is an extensible, open-source MLOps framework for creating portable, production-ready machine learning pipelines. By decoupling infrastructure from code, ZenML enables developers across your organization to collaborate more effectively as they develop to production. ![ZenML Overview](.gitbook/assets/intro_zenml_overview.png) {% tabs %} {% tab title="For MLOps Platform Engineers" %} ZenML enables MLOps infrastructure experts to define, deploy, and manage sophisticated production environments that are easy to share with colleagues. * **ZenML Pro****:** [ZenML Pro](getting-started/zenml-pro/README.md) provides a control plane that allows you to deploy a managed ZenML instance and get access to exciting new features such as CI/CD, Model Control Plane, and RBAC.
* **Self-hosted deployment:** ZenML can be deployed on any cloud provider and provides many Terraform-based utility functions to deploy other MLOps tools or even entire MLOps stacks: ```bash # Connect cloud resources with a simple wizard zenml stack register --provider aws # Deploy entire MLOps stacks at once zenml stack deploy --provider gcp ``` * **Standardization:** With ZenML, you can standardize MLOps infrastructure and tooling across your organization. Simply register your staging and production environments as ZenML stacks and invite your colleagues to run ML workflows on them. ```bash # Register MLOps tools and infrastructure zenml orchestrator register kfp_orchestrator -f kubeflow # Register your production environment zenml stack register production --orchestrator kubeflow ... ``` * Registering your environments as ZenML stacks also enables you to browse and explore them in a convenient user interface. Try it out at [https://www.zenml.io/live-demo](https://www.zenml.io/live-demo)! * **No Vendor Lock-In:** Since infrastructure is decoupled from code, ZenML gives you the freedom to switch to a different tooling stack whenever it suits you. By avoiding vendor lock-in, you have the flexibility to transition between cloud providers or services, ensuring that you receive the best performance and pricing available in the market at any time. ```bash zenml stack set gcp python run.py # Run your ML workflows in GCP zenml stack set aws python run.py # Now your ML workflow runs in AWS ``` :rocket: **Learn More** Ready to deploy and manage your MLOps infrastructure with ZenML? Here is a collection of pages you can take a look at next:
🏗️ Switch to productionSet up and manage production-ready infrastructure with ZenML.cloud-orchestration.md
📋 Component guideExplore the existing infrastructure and tooling integrations of ZenML../component-guide/README.md
🙋 FAQFind answers to the most frequently asked questions.faq.md
{% endtab %} {% tab title="For Data Scientists" %} ZenML gives data scientists the freedom to fully focus on modeling and experimentation while writing code that is production-ready from the get-go. * **Develop Locally:** ZenML allows you to develop ML models in any environment using your favorite tools. This means you can start developing locally, and simply switch to a production environment once you are satisfied with your results. ```bash python run.py # develop your code locally with all your favorite tools zenml stack set production python run.py # run on production infrastructure without any code changes ``` * **Pythonic SDK:** ZenML is designed to be as unintrusive as possible. Adding a ZenML `@step` or `@pipeline` decorator to your Python functions is enough to turn your existing code into ZenML pipelines: ```python from zenml import pipeline, step @step def step_1() -> str: return "world" @step def step_2(input_one: str, input_two: str) -> None: combined_str = input_one + ' ' + input_two print(combined_str) @pipeline def my_pipeline(): output_step_one = step_1() step_2(input_one="hello", input_two=output_step_one) my_pipeline() ``` * **Automatic Metadata Tracking:** ZenML automatically tracks the metadata of all your runs and saves all your datasets and models to disk and versions them. Using the ZenML dashboard, you can see detailed visualizations of all your experiments. Try it out at [https://www.zenml.io/live-demo](https://www.zenml.io/live-demo)! {% hint style="info" %} ZenML integrates seamlessly with many popular open-source tools, so you can also combine ZenML with other popular experiment tracking tools like [Weights & Biases](./component-guide/experiment-trackers/wandb.md), [MLflow](./component-guide/experiment-trackers/mlflow.md), or [Neptune](./component-guide/experiment-trackers/neptune.md) for even better reproducibility. {% endhint %} :rocket: **Learn More** Ready to develop production-ready code with ZenML? Here is a collection of pages you can take a look at next:
🧱 Core ConceptsUnderstand the core concepts behind ZenML.core-concepts.md
🐣 Starter GuideGet started with ZenML and learn how to build your first pipeline and stack.starter-guide
🏃 Quickstart (in Colab)Build your first ZenML pipeline and deploy it in the cloud.https://colab.research.google.com/github/zenml-io/zenml/blob/main/examples/quickstart/notebooks/quickstart.ipynb
{% endtab %} {% tab title="For ML Engineers" %} ZenML empowers ML engineers to take ownership of the entire ML lifecycle end-to-end. Adopting ZenML means fewer handover points and more visibility on what is happening in your organization. * **ML Lifecycle Management:** ZenML's abstractions enable you to manage sophisticated ML setups with ease. After you define your ML workflows as [Pipelines](getting-started/core-concepts.md#1-development) and your development, staging, and production infrastructures as [Stacks](getting-started/core-concepts.md#2-execution), you can move entire ML workflows to different environments in seconds. ```bash zenml stack set staging python run.py # test your workflows on staging infrastructure zenml stack set production python run.py # run your workflows in production ``` * **Reproducibility:** ZenML enables you to painlessly reproduce previous results by automatically tracking and versioning all stacks, pipelines, artifacts, and source code. In the ZenML dashboard, you can get an overview of everything that has happened and drill down into detailed lineage visualizations. Try it out at [https://www.zenml.io/live-demo](https://www.zenml.io/live-demo)!
ZenML Dashboard Overview
* **Automated Deployments:** With ZenML, you no longer need to upload custom Docker images to the cloud whenever you want to deploy a new model to production. Simply define your ML workflow as a ZenML pipeline, let ZenML handle the containerization, and have your model automatically deployed to a highly scalable Kubernetes deployment service like [Seldon](./component-guide/model-deployers/seldon.md). ```python from zenml.integrations.seldon.steps import seldon_model_deployer_step from my_organization.steps import data_loader_step, model_trainer_step @pipeline def my_pipeline(): data = data_loader_step() model = model_trainer_step(data) seldon_model_deployer_step(model) ``` :rocket: **Learn More** Ready to manage your ML lifecycles end-to-end with ZenML? Here is a collection of pages you can take a look at next:
🐣 Starter GuideGet started with ZenML and learn how to build your first pipeline and stack.starter-guide
🐔 How ToDiscover advanced ZenML features like config management and containerization../how-to/pipeline-development/build-pipelines/README.md
🧑‍🏫 ExamplesExplore ZenML through practical use-case examples.https://github.com/zenml-io/zenml-projects
{% endtab %} {% endtabs %}
ZenML Scarf
================ File: docs/book/toc.md ================ # Table of contents ## Getting Started * [Introduction](introduction.md) * [Installation](getting-started/installation.md) * [Core concepts](getting-started/core-concepts.md) * [System Architecture](getting-started/system-architectures.md) * [Deploying ZenML](getting-started/deploying-zenml/README.md) * [Deploy with Docker](getting-started/deploying-zenml/deploy-with-docker.md) * [Deploy with Helm](getting-started/deploying-zenml/deploy-with-helm.md) * [Deploy using HuggingFace Spaces](getting-started/deploying-zenml/deploy-using-huggingface-spaces.md) * [Deploy with custom images](getting-started/deploying-zenml/deploy-with-custom-image.md) * [Secret management](getting-started/deploying-zenml/secret-management.md) * [Custom secret stores](getting-started/deploying-zenml/custom-secret-stores.md) * [ZenML Pro](getting-started/zenml-pro/README.md) * [Core Concepts](getting-started/zenml-pro/core-concepts.md) * [Organizations](getting-started/zenml-pro/organization.md) * [Tenants](getting-started/zenml-pro/tenants.md) * [Teams](getting-started/zenml-pro/teams.md) * [Roles & Permissions](getting-started/zenml-pro/roles.md) * [Self-hosted deployment](getting-started/zenml-pro/self-hosted.md) * [Accessing the ZenML Pro API](getting-started/zenml-pro/pro-api.md) ## User Guide * [Starter guide](user-guide/starter-guide/README.md) * [Create an ML pipeline](user-guide/starter-guide/create-an-ml-pipeline.md) * [Cache previous executions](user-guide/starter-guide/cache-previous-executions.md) * [Manage artifacts](user-guide/starter-guide/manage-artifacts.md) * [Track ML models](user-guide/starter-guide/track-ml-models.md) * [A starter project](user-guide/starter-guide/starter-project.md) * [Production guide](user-guide/production-guide/README.md) * [Deploying ZenML](user-guide/production-guide/deploying-zenml.md) * [Understanding stacks](user-guide/production-guide/understand-stacks.md) * [Connecting remote storage](user-guide/production-guide/remote-storage.md) * [Orchestrate on the cloud](user-guide/production-guide/cloud-orchestration.md) * [Configure your pipeline to add compute](user-guide/production-guide/configure-pipeline.md) * [Configure a code repository](user-guide/production-guide/connect-code-repository.md) * [Set up CI/CD](user-guide/production-guide/ci-cd.md) * [An end-to-end project](user-guide/production-guide/end-to-end.md) * [LLMOps guide](user-guide/llmops-guide/README.md) * [RAG with ZenML](user-guide/llmops-guide/rag-with-zenml/README.md) * [RAG in 85 lines of code](user-guide/llmops-guide/rag-with-zenml/rag-85-loc.md) * [Understanding Retrieval-Augmented Generation (RAG)](user-guide/llmops-guide/rag-with-zenml/understanding-rag.md) * [Data ingestion and preprocessing](user-guide/llmops-guide/rag-with-zenml/data-ingestion.md) * [Embeddings generation](user-guide/llmops-guide/rag-with-zenml/embeddings-generation.md) * [Storing embeddings in a vector database](user-guide/llmops-guide/rag-with-zenml/storing-embeddings-in-a-vector-database.md) * [Basic RAG inference pipeline](user-guide/llmops-guide/rag-with-zenml/basic-rag-inference-pipeline.md) * [Evaluation and metrics](user-guide/llmops-guide/evaluation/README.md) * [Evaluation in 65 lines of code](user-guide/llmops-guide/evaluation/evaluation-in-65-loc.md) * [Retrieval evaluation](user-guide/llmops-guide/evaluation/retrieval.md) * [Generation evaluation](user-guide/llmops-guide/evaluation/generation.md) * [Evaluation in practice](user-guide/llmops-guide/evaluation/evaluation-in-practice.md) * [Reranking for better retrieval](user-guide/llmops-guide/reranking/README.md) * [Understanding reranking](user-guide/llmops-guide/reranking/understanding-reranking.md) * [Implementing reranking in ZenML](user-guide/llmops-guide/reranking/implementing-reranking.md) * [Evaluating reranking performance](user-guide/llmops-guide/reranking/evaluating-reranking-performance.md) * [Improve retrieval by finetuning embeddings](user-guide/llmops-guide/finetuning-embeddings/finetuning-embeddings.md) * [Synthetic data generation](user-guide/llmops-guide/finetuning-embeddings/synthetic-data-generation.md) * [Finetuning embeddings with Sentence Transformers](user-guide/llmops-guide/finetuning-embeddings/finetuning-embeddings-with-sentence-transformers.md) * [Evaluating finetuned embeddings](user-guide/llmops-guide/finetuning-embeddings/evaluating-finetuned-embeddings.md) * [Finetuning LLMs with ZenML](user-guide/llmops-guide/finetuning-llms/finetuning-llms.md) * [Finetuning in 100 lines of code](user-guide/llmops-guide/finetuning-llms/finetuning-100-loc.md) * [Why and when to finetune LLMs](user-guide/llmops-guide/finetuning-llms/why-and-when-to-finetune-llms.md) * [Starter choices with finetuning](user-guide/llmops-guide/finetuning-llms/starter-choices-for-finetuning-llms.md) * [Finetuning with 🤗 Accelerate](user-guide/llmops-guide/finetuning-llms/finetuning-with-accelerate.md) * [Evaluation for finetuning](user-guide/llmops-guide/finetuning-llms/evaluation-for-finetuning.md) * [Deploying finetuned models](user-guide/llmops-guide/finetuning-llms/deploying-finetuned-models.md) * [Next steps](user-guide/llmops-guide/finetuning-llms/next-steps.md) ## How-To * [Manage your ZenML server](how-to/manage-zenml-server/README.md) * [Connect to a server](how-to/manage-zenml-server/connecting-to-zenml/README.md) * [Connect in with your User (interactive)](how-to/manage-zenml-server/connecting-to-zenml/connect-in-with-your-user-interactive.md) * [Connect with a Service Account](how-to/manage-zenml-server/connecting-to-zenml/connect-with-a-service-account.md) * [Upgrade your ZenML server](how-to/manage-zenml-server/upgrade-zenml-server.md) * [Best practices for upgrading ZenML](how-to/manage-zenml-server/best-practices-upgrading-zenml.md) * [Using ZenML server in production](how-to/manage-zenml-server/using-zenml-server-in-prod.md) * [Troubleshoot your ZenML server](how-to/manage-zenml-server/troubleshoot-your-deployed-server.md) * [Migration guide](how-to/manage-zenml-server/migration-guide/migration-guide.md) * [Migration guide 0.13.2 → 0.20.0](how-to/manage-zenml-server/migration-guide/migration-zero-twenty.md) * [Migration guide 0.23.0 → 0.30.0](how-to/manage-zenml-server/migration-guide/migration-zero-thirty.md) * [Migration guide 0.39.1 → 0.41.0](how-to/manage-zenml-server/migration-guide/migration-zero-forty.md) * [Migration guide 0.58.2 → 0.60.0](how-to/manage-zenml-server/migration-guide/migration-zero-sixty.md) * [Project Setup and Management](how-to/project-setup-and-management/README.md) * [Set up a ZenML project](how-to/project-setup-and-management/setting-up-a-project-repository/README.md) * [Set up a repository](how-to/project-setup-and-management/setting-up-a-project-repository/set-up-repository.md) * [Connect your git repository](how-to/project-setup-and-management/setting-up-a-project-repository/connect-your-git-repository.md) * [Collaborate with your team](how-to/project-setup-and-management/collaborate-with-team/README.md) * [Project templates](how-to/project-setup-and-management/collaborate-with-team/project-templates/README.md) * [Create your own template](how-to/project-setup-and-management/collaborate-with-team/project-templates/create-your-own-template.md) * [Shared components for teams](how-to/project-setup-and-management/collaborate-with-team/shared-components-for-teams.md) * [Setting up Stacks, pipelines and models](how-to/project-setup-and-management/collaborate-with-team/stacks-pipelines-models.md) * [Access management](how-to/project-setup-and-management/collaborate-with-team/access-management.md) * [Interact with secrets](how-to/project-setup-and-management/interact-with-secrets.md) * [Pipeline Development](how-to/pipeline-development/README.md) * [Build a pipeline](how-to/pipeline-development/build-pipelines/README.md) * [Use pipeline/step parameters](how-to/pipeline-development/build-pipelines/use-pipeline-step-parameters.md) * [Configuring a pipeline at runtime](how-to/pipeline-development/build-pipelines/configuring-a-pipeline-at-runtime.md) * [Reference environment variables in configurations](how-to/pipeline-development/build-pipelines/reference-environment-variables-in-configurations.md) * [Step output typing and annotation](how-to/pipeline-development/build-pipelines/step-output-typing-and-annotation.md) * [Control caching behavior](how-to/pipeline-development/build-pipelines/control-caching-behavior.md) * [Schedule a pipeline](how-to/pipeline-development/build-pipelines/schedule-a-pipeline.md) * [Deleting a pipeline](how-to/pipeline-development/build-pipelines/delete-a-pipeline.md) * [Compose pipelines](how-to/pipeline-development/build-pipelines/compose-pipelines.md) * [Automatically retry steps](how-to/pipeline-development/build-pipelines/retry-steps.md) * [Run pipelines asynchronously](how-to/pipeline-development/build-pipelines/run-pipelines-asynchronously.md) * [Control execution order of steps](how-to/pipeline-development/build-pipelines/control-execution-order-of-steps.md) * [Using a custom step invocation ID](how-to/pipeline-development/build-pipelines/using-a-custom-step-invocation-id.md) * [Name your pipeline runs](how-to/pipeline-development/build-pipelines/name-your-pipeline-runs.md) * [Tag your pipeline runs](how-to/pipeline-development/build-pipelines/tag-your-pipeline-runs.md) * [Use failure/success hooks](how-to/pipeline-development/build-pipelines/use-failure-success-hooks.md) * [Fan in, fan out](how-to/pipeline-development/build-pipelines/fan-in-fan-out.md) * [Hyperparameter tuning](how-to/pipeline-development/build-pipelines/hyper-parameter-tuning.md) * [Access secrets in a step](how-to/pipeline-development/build-pipelines/access-secrets-in-a-step.md) * [Run an individual step](how-to/pipeline-development/build-pipelines/run-an-individual-step.md) * [Fetching pipelines](how-to/pipeline-development/build-pipelines/fetching-pipelines.md) * [Get past pipeline/step runs](how-to/pipeline-development/build-pipelines/get-past-pipeline-step-runs.md) * [Develop locally](how-to/pipeline-development/develop-locally/README.md) * [Use config files to develop locally](how-to/pipeline-development/develop-locally/local-prod-pipeline-variants.md) * [Keep your pipelines and dashboard clean](how-to/pipeline-development/develop-locally/keep-your-dashboard-server-clean.md) * [Use configuration files](how-to/pipeline-development/use-configuration-files/README.md) * [How to configure a pipeline with a YAML](how-to/pipeline-development/use-configuration-files/how-to-use-config.md) * [What can be configured](how-to/pipeline-development/use-configuration-files/what-can-be-configured.md) * [Runtime settings for Docker, resources, and stack components](how-to/pipeline-development/use-configuration-files/runtime-configuration.md) * [Configuration hierarchy](how-to/pipeline-development/use-configuration-files/configuration-hierarchy.md) * [Find out which configuration was used for a run](how-to/pipeline-development/use-configuration-files/retrieve-used-configuration-of-a-run.md) * [Autogenerate a template yaml file](how-to/pipeline-development/use-configuration-files/autogenerate-a-template-yaml-file.md) * [Train with GPUs](how-to/pipeline-development/training-with-gpus/README.md) * [Distributed Training with 🤗 Accelerate](how-to/pipeline-development/training-with-gpus/accelerate-distributed-training.md) * [Run remote pipelines from notebooks](how-to/pipeline-development/run-remote-notebooks/README.md) * [Limitations of defining steps in notebook cells](how-to/pipeline-development/run-remote-notebooks/limitations-of-defining-steps-in-notebook-cells.md) * [Run a single step from a notebook](how-to/pipeline-development/run-remote-notebooks/run-a-single-step-from-a-notebook.md) * [Configure Python environments](how-to/pipeline-development/configure-python-environments/README.md) * [Handling dependencies](how-to/pipeline-development/configure-python-environments/handling-dependencies.md) * [Configure the server environment](how-to/pipeline-development/configure-python-environments/configure-the-server-environment.md) * [Trigger a pipeline](how-to/trigger-pipelines/README.md) * [Use templates: Python SDK](how-to/trigger-pipelines/use-templates-python.md) * [Use templates: CLI](how-to/trigger-pipelines/use-templates-cli.md) * [Use templates: Dashboard](how-to/trigger-pipelines/use-templates-dashboard.md) * [Use templates: Rest API](how-to/trigger-pipelines/use-templates-rest-api.md) * [Customize Docker builds](how-to/customize-docker-builds/README.md) * [Docker settings on a pipeline](how-to/customize-docker-builds/docker-settings-on-a-pipeline.md) * [Docker settings on a step](how-to/customize-docker-builds/docker-settings-on-a-step.md) * [Use a prebuilt image for pipeline execution](how-to/customize-docker-builds/use-a-prebuilt-image.md) * [Specify pip dependencies and apt packages](how-to/customize-docker-builds/specify-pip-dependencies-and-apt-packages.md) * [How to use a private PyPI repository](how-to/customize-docker-builds/how-to-use-a-private-pypi-repository.md) * [Use your own Dockerfiles](how-to/customize-docker-builds/use-your-own-docker-files.md) * [Which files are built into the image](how-to/customize-docker-builds/which-files-are-built-into-the-image.md) * [How to reuse builds](how-to/customize-docker-builds/how-to-reuse-builds.md) * [Define where an image is built](how-to/customize-docker-builds/define-where-an-image-is-built.md) * [Data and Artifact Management](how-to/data-artifact-management/README.md) * [Understand ZenML artifacts](how-to/data-artifact-management/handle-data-artifacts/README.md) * [How ZenML stores data](how-to/data-artifact-management/handle-data-artifacts/artifact-versioning.md) * [Return multiple outputs from a step](how-to/data-artifact-management/handle-data-artifacts/return-multiple-outputs-from-a-step.md) * [Delete an artifact](how-to/data-artifact-management/handle-data-artifacts/delete-an-artifact.md) * [Artifacts naming](how-to/data-artifact-management/handle-data-artifacts/artifacts-naming.md) * [Organize data with tags](how-to/data-artifact-management/handle-data-artifacts/tagging.md) * [Get arbitrary artifacts in a step](how-to/data-artifact-management/handle-data-artifacts/get-arbitrary-artifacts-in-a-step.md) * [Handle custom data types](how-to/data-artifact-management/handle-data-artifacts/handle-custom-data-types.md) * [Load artifacts into memory](how-to/data-artifact-management/handle-data-artifacts/load-artifacts-into-memory.md) * [Complex use-cases](how-to/data-artifact-management/complex-usecases/README.md) * [Datasets in ZenML](how-to/data-artifact-management/complex-usecases/datasets.md) * [Manage big data](how-to/data-artifact-management/complex-usecases/manage-big-data.md) * [Skipping materialization](how-to/data-artifact-management/complex-usecases/unmaterialized-artifacts.md) * [Passing artifacts between pipelines](how-to/data-artifact-management/complex-usecases/passing-artifacts-between-pipelines.md) * [Register Existing Data as a ZenML Artifact](how-to/data-artifact-management/complex-usecases/registering-existing-data.md) * [Visualizing artifacts](how-to/data-artifact-management/visualize-artifacts/README.md) * [Default visualizations](how-to/data-artifact-management/visualize-artifacts/types-of-visualizations.md) * [Creating custom visualizations](how-to/data-artifact-management/visualize-artifacts/creating-custom-visualizations.md) * [Displaying visualizations in the dashboard](how-to/data-artifact-management/visualize-artifacts/visualizations-in-dashboard.md) * [Disabling visualizations](how-to/data-artifact-management/visualize-artifacts/disabling-visualizations.md) * [Model Management and Metrics](how-to/model-management-metrics/README.md) * [Use the Model Control Plane](how-to/model-management-metrics/model-control-plane/README.md) * [Registering a Model](how-to/model-management-metrics/model-control-plane/register-a-model.md) * [Deleting a Model](how-to/model-management-metrics/model-control-plane/delete-a-model.md) * [Associate a pipeline with a Model](how-to/model-management-metrics/model-control-plane/associate-a-pipeline-with-a-model.md) * [Connecting artifacts via a Model](how-to/model-management-metrics/model-control-plane/connecting-artifacts-via-a-model.md) * [Controlling Model versions](how-to/model-management-metrics/model-control-plane/model-versions.md) * [Load a Model in code](how-to/model-management-metrics/model-control-plane/load-a-model-in-code.md) * [Promote a Model](how-to/model-management-metrics/model-control-plane/promote-a-model.md) * [Linking model binaries/data to a Model](how-to/model-management-metrics/model-control-plane/linking-model-binaries-data-to-models.md) * [Load artifacts from Model](how-to/model-management-metrics/model-control-plane/load-artifacts-from-model.md) * [Track metrics and metadata](how-to/model-management-metrics/track-metrics-metadata/README.md) * [Attach metadata to a step](how-to/model-management-metrics/track-metrics-metadata/attach-metadata-to-a-step.md) * [Attach metadata to a run](how-to/model-management-metrics/track-metrics-metadata/attach-metadata-to-a-run.md) * [Attach metadata to an artifact](how-to/model-management-metrics/track-metrics-metadata/attach-metadata-to-an-artifact.md) * [Attach metadata to a model](how-to/model-management-metrics/track-metrics-metadata/attach-metadata-to-a-model.md) * [Group metadata](how-to/model-management-metrics/track-metrics-metadata/grouping-metadata.md) * [Special Metadata Types](how-to/model-management-metrics/track-metrics-metadata/logging-metadata.md) * [Fetch metadata within steps](how-to/model-management-metrics/track-metrics-metadata/fetch-metadata-within-steps.md) * [Fetch metadata during pipeline composition](how-to/model-management-metrics/track-metrics-metadata/fetch-metadata-within-pipeline.md) * [Stack infrastructure and deployment](how-to/infrastructure-deployment/README.md) * [Manage stacks & components](how-to/infrastructure-deployment/stack-deployment/README.md) * [Deploy a cloud stack with ZenML](how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack.md) * [Deploy a cloud stack with Terraform](how-to/infrastructure-deployment/stack-deployment/deploy-a-cloud-stack-with-terraform.md) * [Register a cloud stack](how-to/infrastructure-deployment/stack-deployment/register-a-cloud-stack.md) * [Export and install stack requirements](how-to/infrastructure-deployment/stack-deployment/export-stack-requirements.md) * [Reference secrets in stack configuration](how-to/infrastructure-deployment/stack-deployment/reference-secrets-in-stack-configuration.md) * [Implement a custom stack component](how-to/infrastructure-deployment/stack-deployment/implement-a-custom-stack-component.md) * [Infrastructure as code](how-to/infrastructure-deployment/infrastructure-as-code/README.md) * [Manage your stacks with Terraform](how-to/infrastructure-deployment/infrastructure-as-code/terraform-stack-management.md) * [ZenML & Terraform Best Practices](how-to/infrastructure-deployment/infrastructure-as-code/best-practices.md) * [Connect services via connectors](how-to/infrastructure-deployment/auth-management/README.md) * [Service Connectors guide](how-to/infrastructure-deployment/auth-management/service-connectors-guide.md) * [Security best practices](how-to/infrastructure-deployment/auth-management/best-security-practices.md) * [Docker Service Connector](how-to/infrastructure-deployment/auth-management/docker-service-connector.md) * [Kubernetes Service Connector](how-to/infrastructure-deployment/auth-management/kubernetes-service-connector.md) * [AWS Service Connector](how-to/infrastructure-deployment/auth-management/aws-service-connector.md) * [GCP Service Connector](how-to/infrastructure-deployment/auth-management/gcp-service-connector.md) * [Azure Service Connector](how-to/infrastructure-deployment/auth-management/azure-service-connector.md) * [HyperAI Service Connector](how-to/infrastructure-deployment/auth-management/hyperai-service-connector.md) * [Control logging](how-to/control-logging/README.md) * [View logs on the dashboard](how-to/control-logging/view-logs-on-the-dasbhoard.md) * [Enable or disable logs storage](how-to/control-logging/enable-or-disable-logs-storing.md) * [Set logging verbosity](how-to/control-logging/set-logging-verbosity.md) * [Disable `rich` traceback output](how-to/control-logging/disable-rich-traceback.md) * [Disable colorful logging](how-to/control-logging/disable-colorful-logging.md) * [Popular integrations](how-to/popular-integrations/README.md) * [Run on AWS](how-to/popular-integrations/aws-guide.md) * [Run on GCP](how-to/popular-integrations/gcp-guide.md) * [Run on Azure](how-to/popular-integrations/azure-guide.md) * [Kubeflow](how-to/popular-integrations/kubeflow.md) * [Kubernetes](how-to/popular-integrations/kubernetes.md) * [MLflow](how-to/popular-integrations/mlflow.md) * [Skypilot](how-to/popular-integrations/skypilot.md) * [Contribute to/Extend ZenML](how-to/contribute-to-zenml/README.md) * [Implement a custom integration](how-to/contribute-to-zenml/implement-a-custom-integration.md) * [Debug and solve issues](how-to/debug-and-solve-issues.md) ## Stack Components * [Overview](component-guide/README.md) * [Orchestrators](component-guide/orchestrators/orchestrators.md) * [Local Orchestrator](component-guide/orchestrators/local.md) * [Local Docker Orchestrator](component-guide/orchestrators/local-docker.md) * [Kubeflow Orchestrator](component-guide/orchestrators/kubeflow.md) * [Kubernetes Orchestrator](component-guide/orchestrators/kubernetes.md) * [Google Cloud VertexAI Orchestrator](component-guide/orchestrators/vertex.md) * [AWS Sagemaker Orchestrator](component-guide/orchestrators/sagemaker.md) * [AzureML Orchestrator](component-guide/orchestrators/azureml.md) * [Databricks Orchestrator](component-guide/orchestrators/databricks.md) * [Tekton Orchestrator](component-guide/orchestrators/tekton.md) * [Airflow Orchestrator](component-guide/orchestrators/airflow.md) * [Skypilot VM Orchestrator](component-guide/orchestrators/skypilot-vm.md) * [HyperAI Orchestrator](component-guide/orchestrators/hyperai.md) * [Lightning AI Orchestrator](component-guide/orchestrators/lightning.md) * [Develop a custom orchestrator](component-guide/orchestrators/custom.md) * [Artifact Stores](component-guide/artifact-stores/artifact-stores.md) * [Local Artifact Store](component-guide/artifact-stores/local.md) * [Amazon Simple Cloud Storage (S3)](component-guide/artifact-stores/s3.md) * [Google Cloud Storage (GCS)](component-guide/artifact-stores/gcp.md) * [Azure Blob Storage](component-guide/artifact-stores/azure.md) * [Develop a custom artifact store](component-guide/artifact-stores/custom.md) * [Container Registries](component-guide/container-registries/container-registries.md) * [Default Container Registry](component-guide/container-registries/default.md) * [DockerHub](component-guide/container-registries/dockerhub.md) * [Amazon Elastic Container Registry (ECR)](component-guide/container-registries/aws.md) * [Google Cloud Container Registry](component-guide/container-registries/gcp.md) * [Azure Container Registry](component-guide/container-registries/azure.md) * [GitHub Container Registry](component-guide/container-registries/github.md) * [Develop a custom container registry](component-guide/container-registries/custom.md) * [Data Validators](component-guide/data-validators/data-validators.md) * [Great Expectations](component-guide/data-validators/great-expectations.md) * [Deepchecks](component-guide/data-validators/deepchecks.md) * [Evidently](component-guide/data-validators/evidently.md) * [Whylogs](component-guide/data-validators/whylogs.md) * [Develop a custom data validator](component-guide/data-validators/custom.md) * [Experiment Trackers](component-guide/experiment-trackers/experiment-trackers.md) * [Comet](component-guide/experiment-trackers/comet.md) * [MLflow](component-guide/experiment-trackers/mlflow.md) * [Neptune](component-guide/experiment-trackers/neptune.md) * [Weights & Biases](component-guide/experiment-trackers/wandb.md) * [Google Cloud VertexAI Experiment Tracker](component-guide/experiment-trackers/vertexai.md) * [Develop a custom experiment tracker](component-guide/experiment-trackers/custom.md) * [Model Deployers](component-guide/model-deployers/model-deployers.md) * [MLflow](component-guide/model-deployers/mlflow.md) * [Seldon](component-guide/model-deployers/seldon.md) * [BentoML](component-guide/model-deployers/bentoml.md) * [Hugging Face](component-guide/model-deployers/huggingface.md) * [Databricks](component-guide/model-deployers/databricks.md) * [vLLM](component-guide/model-deployers/vllm.md) * [Develop a Custom Model Deployer](component-guide/model-deployers/custom.md) * [Step Operators](component-guide/step-operators/step-operators.md) * [Amazon SageMaker](component-guide/step-operators/sagemaker.md) * [AzureML](component-guide/step-operators/azureml.md) * [Google Cloud VertexAI](component-guide/step-operators/vertex.md) * [Kubernetes](component-guide/step-operators/kubernetes.md) * [Modal](component-guide/step-operators/modal.md) * [Spark](component-guide/step-operators/spark-kubernetes.md) * [Develop a Custom Step Operator](component-guide/step-operators/custom.md) * [Alerters](component-guide/alerters/alerters.md) * [Discord Alerter](component-guide/alerters/discord.md) * [Slack Alerter](component-guide/alerters/slack.md) * [Develop a Custom Alerter](component-guide/alerters/custom.md) * [Image Builders](component-guide/image-builders/image-builders.md) * [Local Image Builder](component-guide/image-builders/local.md) * [Kaniko Image Builder](component-guide/image-builders/kaniko.md) * [AWS Image Builder](component-guide/image-builders/aws.md) * [Google Cloud Image Builder](component-guide/image-builders/gcp.md) * [Develop a Custom Image Builder](component-guide/image-builders/custom.md) * [Annotators](component-guide/annotators/annotators.md) * [Argilla](component-guide/annotators/argilla.md) * [Label Studio](component-guide/annotators/label-studio.md) * [Pigeon](component-guide/annotators/pigeon.md) * [Prodigy](component-guide/annotators/prodigy.md) * [Develop a Custom Annotator](component-guide/annotators/custom.md) * [Model Registries](component-guide/model-registries/model-registries.md) * [MLflow Model Registry](component-guide/model-registries/mlflow.md) * [Develop a Custom Model Registry](component-guide/model-registries/custom.md) * [Feature Stores](component-guide/feature-stores/feature-stores.md) * [Feast](component-guide/feature-stores/feast.md) * [Develop a Custom Feature Store](component-guide/feature-stores/custom.md) ## Examples * [Quickstart](https://github.com/zenml-io/zenml/blob/main/examples/quickstart) * [End-to-End Batch Inference](https://github.com/zenml-io/zenml/tree/main/examples/e2e) * [Basic NLP with BERT](https://github.com/zenml-io/zenml/tree/main/examples/e2e\_nlp) * [Computer Vision with YoloV8](https://github.com/zenml-io/zenml-projects/tree/main/end-to-end-computer-vision) * [LLM Finetuning](https://github.com/zenml-io/zenml/tree/main/examples/llm\_finetuning) * [More Projects...](https://github.com/zenml-io/zenml-projects) ## Reference * [Python Client](reference/python-client.md) * [Global settings](reference/global-settings.md) * [Environment Variables](reference/environment-variables.md) * [API reference](reference/api-reference.md) * [SDK & CLI reference](https://sdkdocs.zenml.io/) * [How do I...?](reference/how-do-i.md) * [Community & content](reference/community-and-content.md) * [FAQ](reference/faq.md)