ZenML 管道 YAML 配置完全指南:用配置文件解耦代码、参数与运行环境
2026/9/18 13:33:31 网站建设 项目流程

ZenML 管道 YAML 配置完全指南:用配置文件解耦代码、参数与运行环境

【免费下载链接】zenmlZenML 🙏: One AI Platform from Pipelines to Agents. https://zenml.io.项目地址: https://gitcode.com/GitHub_Trending/ze/zenml

ZenML 允许通过 YAML 配置文件在不改动任何 Python 代码的前提下,覆盖管道(Pipeline)与步骤(Step)的运行行为,包括参数、缓存策略、Docker 镜像、计算资源、调度计划与模型关联等。本文以官方文档docs/book/how-to/steps-pipelines/yaml_configuration.md为核心骨架,结合仓库源码(如src/zenml/pipelines/pipeline_definition.pysrc/zenml/config/下的配置模型)深入讲解配置解析层级、每个配置项的底层字段语义与真实命令行用法,读完后你可以直接为任意 ZenML 管道编写可复用的 YAML 配置。

为什么需要 YAML 配置

ZenML 管道本身由 Python 代码定义,但“如何运行”往往与“运行什么”是两回事。YAML 配置能力让你可以:

  • 配置与代码分离:换环境、换参数、换资源规格时只改 YAML,不动代码;
  • 实验不同参数组合:同一管道搭配多份配置反复试跑;
  • 保证可复现性:将配置随管道、步骤与运行记录一并固化,任何人可以用同一份 YAML 复现同样的运行。

在 ZenML 中,一份 YAML 配置会被解析为PipelineRunConfiguration对象(定义于 pipeline_run_configuration.py),其中包含run_nameenable_cacheenable_artifact_metadataenable_artifact_visualizationenable_step_logsenable_pipeline_logsschedulebuildstepssettingsenvironmentsecretstagsmodelparametersretry等全部运行级配置字段。

基本用法:一行代码挂载配置

在运行管道时传入config_path即可应用配置文件:

my_pipeline.with_options(config_path="config.yaml")()

在源码层面,with_options(见 pipeline_definition.py)会拷贝管道实例并应用配置;真正执行时,_compile方法(pipeline_definition.py)会调用_parse_config_file读取 YAML 文件,再将其与代码中显式传入的选项合并。这意味着“改配置不改代码”是字面意义上的:同一管道对象可以挂不同的config_path跑出完全不同的运行。

一份最小的示例配置

# Enable/disable features enable_cache: False enable_step_logs: True # Pipeline parameters parameters: dataset_name: "my_dataset" learning_rate: 0.01 # Step-specific configuration steps: train_model: parameters: learning_rate: 0.001 # Override the pipeline parameter for this step enable_cache: True # Override the pipeline cache setting

这份配置做了三件事:全局关闭缓存、开启步骤日志、给管道注入两个参数,同时单独给train_model步骤覆盖学习率并重新开启缓存。

配置解析层级(优先级)

ZenML 解析配置时遵循严格优先级,从高到低为:

  1. 运行时 Python 代码——最高优先级。即with_options(...)中以关键字参数显式传入的值(如run_nameschedulesettings等)。源码中_compile会先解析配置文件,再用代码参数构造的PipelineRunConfiguration通过pydantic_utils.update_model覆盖前者,注释明确写着“Update with the values in code so they take precedence”(pipeline_definition.py);

  2. 步骤级 YAML 配置——覆盖管道级设置:

    steps: train_model: parameters: learning_rate: 0.001 # Overrides pipeline-level setting
  3. 管道级 YAML 配置——作为各步骤的默认值:

    parameters: learning_rate: 0.01 # Lower precedence than step-level
  4. 代码中的默认值——最低优先级,即定义管道/步骤函数时给出的默认参数。

这一层级设计让你可以在管道级定义“基准配置”,再针对个别步骤做细粒度覆盖,无需复制整段配置。

管道与步骤参数(parameters)

parameters与你在 Python 中传给管道、步骤函数的参数一一对应:

# Pipeline parameters parameters: dataset_name: "my_dataset" learning_rate: 0.01 batch_size: 32 epochs: 10 # Step parameters steps: preprocessing: parameters: normalize: True fill_missing: "mean" train_model: parameters: learning_rate: 0.001 # Override the pipeline parameter optimizer: "adam"

从源码看,管道级parameters对应PipelineRunConfiguration.parameters(类型为Dict[str, Any]),步骤级parameters对应StepConfigurationUpdate.parameters(见 step_configurations.py),它们在编译阶段被注入到管道入口函数与步骤函数的实参中,因此必须与函数签名中定义的参数名、类型保持一致,否则编译会失败。

布尔开关(Enable Flags)

这些布尔标志控制管道执行层面的若干行为,对应PipelineRunConfigurationStepConfigurationUpdate中的同名可选布尔字段:

# Pipeline-level flags enable_artifact_metadata: True # Whether to collect and store metadata for artifacts enable_artifact_visualization: True # Whether to generate visualizations for artifacts enable_cache: True # Whether to use caching for steps enable_step_logs: True # Whether to capture and store step logs # Step-specific flags steps: preprocessing: enable_cache: False # Disable caching for this step only train_model: enable_artifact_visualization: False # Disable visualizations for this step

各字段语义(依据源码字段注释):

  • enable_cache:是否启用步骤缓存(命中缓存时跳过步骤重算);
  • enable_artifact_metadata:是否采集并存储产出 Artifact 的元数据;
  • enable_artifact_visualization:是否为产出 Artifact 生成可视化;
  • enable_step_logs:是否捕获并存储步骤日志;
  • 此外PipelineRunConfiguration还支持enable_pipeline_logs(管道级日志)与enable_heartbeat(步骤心跳,用于长时间运行任务保活)等字段,均可按需写入 YAML。

设置运行名称(run_name)

run_name为一次管道运行指定自定义名称:

run_name: "training_run_cifar10_resnet50_lr0.001"

重要限制:管道运行名称在同一个项目内必须唯一,重复名称会直接报错。三种避免冲突的做法:

  1. 使用动态占位符保证唯一性:

    # Example 1: Use placeholders for date and time to ensure uniqueness run_name: "training_run_{date}_{time}" # Example 2: Combine placeholders with specific details for better context run_name: "training_run_cifar10_resnet50_lr0.001_{date}_{time}"
  2. 删除配置中的run_name,让 ZenML 自动生成唯一名称;

  3. 每次重跑前更换run_name

可用占位符包括{date}{time}以及你在管道配置中定义的任意参数。在源码层面,PipelineConfigurationUpdate.finalize_substitutions(见 pipeline_configurations.py)会在运行时注入{date}(格式%Y_%m_%d)与{time}(格式%H_%M_%S_%f,精确到微秒),因此只要包含{time}基本不可能重名。

资源与组件配置

Docker 设置

settings.docker控制管道以容器方式执行时的镜像构建行为,对应DockerSettings类(docker_settings.py):

settings: docker: # Packages to install via apt-get apt_packages: ["curl", "git", "libgomp1"] # Whether to copy files from current directory to the Docker image copy_files: True # Environment variables to set in the container environment: ZENML_LOGGING_VERBOSITY: DEBUG PYTHONUNBUFFERED: "1" # Parent image to use for building parent_image: "zenml-io/zenml-cuda:latest" # Additional Python packages to install requirements: ["torch==1.10.0", "transformers>=4.0.0", "pandas"]

结合源码补充几个关键字段的细节:

  • parent_image:镜像构建的父镜像,默认使用与当前 Python/ZenML 版本匹配的官方镜像;若自定义镜像必须确保其中已安装 ZenML;若同时指定了dockerfileparent_image会被忽略;
  • requirements:接受一个 pip 包列表或指向 requirements 文件的路径,构建时通过 pip 安装;
  • environment/runtime_environment:前者在安装依赖注入环境变量,后者在依赖安装注入;
  • copy_files:是否把当前目录下的文件复制进镜像;
  • 更多可选字段还包括dockerfilebuild_context_rootskip_buildprevent_build_reusereplicate_local_python_environmentinstall_stack_requirementsrequired_integrationstarget_repository等。依赖安装遵循固定顺序:本机pip freeze导出的包 → 栈组件所需的包(可用install_stack_requirements: False关闭)→required_integrations的依赖 →pyproject_path指向的pyproject.toml依赖 →requirements字段。若以上均未指定,ZenML 会自动探测源码根目录下的requirements.txtpyproject.toml,可用disable_automatic_requirements_detection: True关闭。

资源设置

settings.resources控制步骤或管道获得的计算资源,对应ResourceSettings类(resource_settings.py):

# Pipeline-level resource settings settings: resources: cpu_count: 2 gpu_count: 1 memory: "4Gb" # Step-specific resource settings steps: train_model: settings: resources: cpu_count: 4 gpu_count: 2 memory: "16Gb"

字段说明:

  • cpu_count:申请的 CPU 核数;
  • gpu_count:申请的 GPU 数量;
  • memory:内存大小,需匹配MEMORY_REGEX^[0-9]+(B|KB|MB|GB|TB|PB|...)等字节单位,大小写敏感),如"4Gb""16Gb"
  • preemptible:是否允许使用可抢占资源(仅在使用 ZenML 资源池时生效);
  • 面向部署场景还可配置min_replicas/max_replicas(副本与弹性伸缩范围)、autoscaling_metric"cpu""memory""concurrency""rps")、autoscaling_targetmax_concurrency等。

栈组件设置

可以为单个步骤指定使用哪个已注册的栈组件,并为其传入组件专属配置:

steps: train_model: # Use specific named components experiment_tracker: "mlflow_tracker" step_operator: "vertex_gpu" # Component-specific settings settings: # MLflow specific configuration experiment_tracker.mlflow: experiment_name: "image_classification" nested: True
  • experiment_trackerstep_operator对应StepConfigurationUpdate中同名可选字段(接受组件名称字符串),可把某一步的计算卸载到远程 step operator(如 Vertex AI、SageMaker)或将实验记录写入指定 tracker;
  • settings下按组件类型.组件flavor的键组织(如experiment_tracker.mlflow),这些键最终由settings字典(Dict[str, SerializeAsAny[BaseSettings]])承载,具体字段随 flavor 而定。

配置文件的工作流技巧

自动生成配置模板

ZenML 提供了生成模板配置文件的命令:

zenml pipeline build-configuration my_pipeline > config.yaml

该命令输出包含管道参数、步骤参数及各项配置选项(含默认值)的完整 YAML,可作为手写配置的起点。此外,当前 CLI 的zenml pipeline runzenml pipeline buildzenml pipeline deploy子命令均支持--config/-c参数直接挂载 YAML(见 cli/pipeline.py),例如:

zenml pipeline run my_module.my_pipeline --config configs/prod.yaml zenml pipeline build my_module.my_pipeline --config config.yaml -o build.yaml

其中zenml pipeline run还支持--stack指定栈、--build复用既有构建、--prevent-build-reuse禁止构建复用;zenml pipeline build支持--output将构建信息写为 YAML 文件。

在配置中引用环境变量

YAML 配置内可直接引用宿主机环境变量:

settings: docker: environment: # References an environment variable from the host system API_KEY: ${MY_API_KEY} DATABASE_URL: ${DB_CONNECTION_STRING}

源码中,_compile在合并完代码覆盖项后,会对整个run_config调用substitute_env_variable_placeholders(见 env_utils.py),将所有${VAR}占位符替换为os.environ中的实际值。注意:若引用的环境变量未设置,默认会抛出KeyError而不是静默替换为空,这能避免把错误的空值带入云端运行。

用多份配置管理多环境

常见做法是为每个环境维护一份配置:

├── configs/ │ ├── dev.yaml # Development configuration │ ├── staging.yaml # Staging configuration │ └── prod.yaml # Production configuration

示例开发配置:

# dev.yaml enable_cache: False enable_step_logs: True parameters: dataset_size: "small" settings: docker: parent_image: "zenml-io/zenml:latest"

示例生产配置:

# prod.yaml enable_cache: True enable_step_logs: False parameters: dataset_size: "full" settings: docker: parent_image: "zenml-io/zenml-cuda:latest" resources: cpu_count: 8 memory: "16Gb"

运行时按需选择:

# For development my_pipeline.with_options(config_path="configs/dev.yaml")() # For production my_pipeline.with_options(config_path="configs/prod.yaml")()

开发环境关闭缓存、使用轻量镜像加快迭代;生产环境开启缓存、使用 CUDA 镜像并申请大内存,参数dataset_size也随环境切换。

高级配置

模型配置

通过model将管道关联到一个 ZenML Model,用于统一管理模型工件、版本与元数据:

model: name: "classification_model" description: "Image classifier trained on the CIFAR-10 dataset" tags: ["computer-vision", "classification", "pytorch"] # Specific model version version: "1.2.3"

PipelineRunConfiguration.model对应Model对象(解析时经Model.model_validate校验,见_parse_config_file),支持namedescriptiontagsversion等字段;步骤级也可通过steps.<name>.model单独关联模型。

调度设置

当编排器(orchestrator)支持调度时,可通过schedule定时触发管道:

schedule: # Whether to run the pipeline for past dates if schedule is missed catchup: false # Cron expression for scheduling (daily at midnight) cron_expression: "0 0 * * *" # Time to start scheduling from start_time: "2023-06-01T00:00:00Z"

scheduleSchedule模型承载(schedule.py),可用字段还包括:

  • cron_expression:cron 表达式,设置后优先于“起始时间 + 间隔”方式;
  • start_time/end_time:调度起止时间,未带时区的 datetime 会被视为本地时区(源码中_ensure_timezone校验器会发出警告并按本地时区处理);
  • interval_second:周期调度的间隔秒数;
  • catchup:错过调度时是否补跑;若你的管道内部自行处理回填,建议设False避免重复回填;
  • run_once_start_time:仅运行一次的时间点。

从源码看配置如何被编译

理解底层流程有助于排查配置不生效的问题。_compile(pipeline_definition.py)的完整链路为:

  1. _parse_config_file(config_path, matcher=list(PipelineRunConfiguration.model_fields.keys())):用yaml.SafeLoader读取 YAML,并只保留PipelineRunConfiguration已声明字段的键(见 pipeline_definition.py);
  2. 用解析结果构造PipelineRunConfiguration
  3. 将代码中传入的run_configuration_argsrun_nameschedulesettings等)构造为另一个PipelineRunConfiguration,通过update_model合并——代码值覆盖文件值
  4. 对合并结果执行${VAR}环境变量占位符替换;
  5. 交给Compiler().compile(...)生成管道快照,随后快照同样执行环境变量替换,最终提交执行。

因此:代码 > 文件、步骤 > 管道、管道 > 默认值的优先级顺序,是由“配置文件先解析、代码后覆盖”的合并逻辑在源码层面保证的;而配置文件中的键名必须与PipelineRunConfiguration/StepConfigurationUpdate字段名严格一致,未知键会被直接过滤掉(不报错也不生效),这也是值得注意的排查点。

小结

YAML 配置是 ZenML 中把“管道定义”与“运行方式”解耦的核心机制:with_options(config_path=...)一处挂载,即可覆盖参数、缓存与日志开关、运行名称、Docker 镜像、计算资源、栈组件选择、模型关联与调度计划,并通过“代码 > 步骤 > 管道 > 默认值”的层级让配置既可全局复用、又可局部覆盖。配合zenml pipeline run/build/deploy --config命令与${VAR}环境变量替换,你可以在不改动一行业务代码的前提下,让同一套管道在开发、预发、生产环境之间无缝切换,同时保证每次运行的可复现性。

延伸阅读:

  • Steps & Pipelines - 管道与步骤核心概念
  • Advanced Features - 缓存、日志等高级管道特性

【免费下载链接】zenmlZenML 🙏: One AI Platform from Pipelines to Agents. https://zenml.io.项目地址: https://gitcode.com/GitHub_Trending/ze/zenml

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询