ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

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

ZenML 管道 YAML 配置完全指南:用配置文件解耦代码、参数与运行环境 ZenML 管道 YAML 配置完全指南用配置文件解耦代码、参数与运行环境【免费下载链接】zenmlZenML : One AI Platform from Pipelines to Agents. https://zenml.io.项目地址: https://gitcode.com/GitHub_Trending/ze/zenmlZenML 允许通过 YAML 配置文件在不改动任何 Python 代码的前提下覆盖管道Pipeline与步骤Step的运行行为包括参数、缓存策略、Docker 镜像、计算资源、调度计划与模型关联等。本文以官方文档docs/book/how-to/steps-pipelines/yaml_configuration.md为核心骨架结合仓库源码如src/zenml/pipelines/pipeline_definition.py、src/zenml/config/下的配置模型深入讲解配置解析层级、每个配置项的底层字段语义与真实命令行用法读完后你可以直接为任意 ZenML 管道编写可复用的 YAML 配置。为什么需要 YAML 配置ZenML 管道本身由 Python 代码定义但“如何运行”往往与“运行什么”是两回事。YAML 配置能力让你可以配置与代码分离换环境、换参数、换资源规格时只改 YAML不动代码实验不同参数组合同一管道搭配多份配置反复试跑保证可复现性将配置随管道、步骤与运行记录一并固化任何人可以用同一份 YAML 复现同样的运行。在 ZenML 中一份 YAML 配置会被解析为PipelineRunConfiguration对象定义于 pipeline_run_configuration.py其中包含run_name、enable_cache、enable_artifact_metadata、enable_artifact_visualization、enable_step_logs、enable_pipeline_logs、schedule、build、steps、settings、environment、secrets、tags、model、parameters、retry等全部运行级配置字段。基本用法一行代码挂载配置在运行管道时传入config_path即可应用配置文件my_pipeline.with_options(config_pathconfig.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 解析配置时遵循严格优先级从高到低为运行时 Python 代码——最高优先级。即with_options(...)中以关键字参数显式传入的值如run_name、schedule、settings等。源码中_compile会先解析配置文件再用代码参数构造的PipelineRunConfiguration通过pydantic_utils.update_model覆盖前者注释明确写着“Update with the values in code so they take precedence”pipeline_definition.py步骤级 YAML 配置——覆盖管道级设置steps: train_model: parameters: learning_rate: 0.001 # Overrides pipeline-level setting管道级 YAML 配置——作为各步骤的默认值parameters: learning_rate: 0.01 # Lower precedence than step-level代码中的默认值——最低优先级即定义管道/步骤函数时给出的默认参数。这一层级设计让你可以在管道级定义“基准配置”再针对个别步骤做细粒度覆盖无需复制整段配置。管道与步骤参数parametersparameters与你在 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这些布尔标志控制管道执行层面的若干行为对应PipelineRunConfiguration与StepConfigurationUpdate中的同名可选布尔字段# 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_namerun_name为一次管道运行指定自定义名称run_name: training_run_cifar10_resnet50_lr0.001重要限制管道运行名称在同一个项目内必须唯一重复名称会直接报错。三种避免冲突的做法使用动态占位符保证唯一性# 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}删除配置中的run_name让 ZenML 自动生成唯一名称每次重跑前更换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.pysettings: 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: [torch1.10.0, transformers4.0.0, pandas]结合源码补充几个关键字段的细节parent_image镜像构建的父镜像默认使用与当前 Python/ZenML 版本匹配的官方镜像若自定义镜像必须确保其中已安装 ZenML若同时指定了dockerfileparent_image会被忽略requirements接受一个 pip 包列表或指向 requirements 文件的路径构建时通过 pip 安装environment/runtime_environment前者在安装依赖前注入环境变量后者在依赖安装后注入copy_files是否把当前目录下的文件复制进镜像更多可选字段还包括dockerfile、build_context_root、skip_build、prevent_build_reuse、replicate_local_python_environment、install_stack_requirements、required_integrations、target_repository等。依赖安装遵循固定顺序本机pip freeze导出的包 → 栈组件所需的包可用install_stack_requirements: False关闭→required_integrations的依赖 →pyproject_path指向的pyproject.toml依赖 →requirements字段。若以上均未指定ZenML 会自动探测源码根目录下的requirements.txt或pyproject.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、16Gbpreemptible是否允许使用可抢占资源仅在使用 ZenML 资源池时生效面向部署场景还可配置min_replicas/max_replicas副本与弹性伸缩范围、autoscaling_metriccpu、memory、concurrency、rps、autoscaling_target与max_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: Trueexperiment_tracker与step_operator对应StepConfigurationUpdate中同名可选字段接受组件名称字符串可把某一步的计算卸载到远程 step operator如 Vertex AI、SageMaker或将实验记录写入指定 trackersettings下按组件类型.组件flavor的键组织如experiment_tracker.mlflow这些键最终由settings字典Dict[str, SerializeAsAny[BaseSettings]]承载具体字段随 flavor 而定。配置文件的工作流技巧自动生成配置模板ZenML 提供了生成模板配置文件的命令zenml pipeline build-configuration my_pipeline config.yaml该命令输出包含管道参数、步骤参数及各项配置选项含默认值的完整 YAML可作为手写配置的起点。此外当前 CLI 的zenml pipeline run、zenml pipeline build、zenml 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_pathconfigs/dev.yaml)() # For production my_pipeline.with_options(config_pathconfigs/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.3PipelineRunConfiguration.model对应Model对象解析时经Model.model_validate校验见_parse_config_file支持name、description、tags、version等字段步骤级也可通过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:00Zschedule由Schedule模型承载schedule.py可用字段还包括cron_expressioncron 表达式设置后优先于“起始时间 间隔”方式start_time/end_time调度起止时间未带时区的 datetime 会被视为本地时区源码中_ensure_timezone校验器会发出警告并按本地时区处理interval_second周期调度的间隔秒数catchup错过调度时是否补跑若你的管道内部自行处理回填建议设False避免重复回填run_once_start_time仅运行一次的时间点。从源码看配置如何被编译理解底层流程有助于排查配置不生效的问题。_compilepipeline_definition.py的完整链路为_parse_config_file(config_path, matcherlist(PipelineRunConfiguration.model_fields.keys()))用yaml.SafeLoader读取 YAML并只保留PipelineRunConfiguration已声明字段的键见 pipeline_definition.py用解析结果构造PipelineRunConfiguration将代码中传入的run_configuration_argsrun_name、schedule、settings等构造为另一个PipelineRunConfiguration通过update_model合并——代码值覆盖文件值对合并结果执行${VAR}环境变量占位符替换交给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),仅供参考
返回列表