容器化 Python 组件

创建具有更复杂依赖关系的 Python 组件

以下假设您对轻量级 Python 组件有基本了解。

容器化 Python 组件扩展了轻量级 Python 组件,放宽了轻量级 Python 组件必须是自包含(即完全独立)的约束。这意味着容器化 Python 组件函数可以依赖于函数外部定义的符号、函数外部的导入、相邻 Python 模块中的代码等。为此,KFP SDK 提供了一种便捷的方式将您的 Python 代码打包到容器中。

作为一种生产软件的最佳实践,当组件指定了packages_to_install时,组件作者应该优先使用容器化 Python 组件,而不是轻量级 Python 组件,因为 KFP SDK 会在构建时将这些依赖项安装到组件镜像中,而不是在任务运行时安装。

以下展示了如何通过修改轻量级 Python 组件示例中的 add 组件来使用容器化 Python 组件

from kfp import dsl

@dsl.component
def add(a: int, b: int) -> int:
    return a + b

1. 源代码设置

首先创建一个空的 src/ 目录来存放您的源代码

src/

接下来,添加以下简单的模块 src/math_utils.py,其中包含一个辅助函数

# src/math_utils.py
def add_numbers(num1, num2):
    return num1 + num2

最后,将您的组件移动到 src/my_component.py 并修改它以使用辅助函数

# src/my_component.py
from kfp import dsl

@dsl.component
def add(a: int, b: int) -> int:
    from math_utils import add_numbers
    return add_numbers(a, b)

src 现在看起来像这样

src/
├── my_component.py
└── math_utils.py

2. 修改 dsl.component 装饰器

在此步骤中,您将在 src/my_component.py 中为您组件的 @dsl.component 装饰器提供 base_imagetarget_image 参数

@dsl.component(base_image='python:3.11',
               target_image='gcr.io/my-project/my-component:v1')
def add(a: int, b: int) -> int:
    from math_utils import add_numbers
    return add_numbers(a, b)

设置 target_image 既 (a) 指定了您将在步骤 3 中构建的镜像的标签,又 (b) 指示 KFP 在使用该标签镜像的容器中运行被装饰的 Python 函数。

在容器化 Python 组件中,base_image 指定了 KFP 在构建新容器镜像时将使用的基础镜像。具体来说,KFP 会在构建镜像所用的 Dockerfile 中,将 base_image 参数用于FROM 指令。

上一个示例包含 base_image 是为了清晰起见,但这并非必需,因为如果省略 base_image,它将默认设置为 'python:3.11'

3. 构建组件

现在您的代码位于独立的目录中,并且您已经指定了目标镜像,您可以使用kfp component build CLI 命令方便地构建镜像

kfp component build src/ --component-filepattern my_component.py --no-push-image

如果您已配置 Docker 使用私有镜像仓库,您可以将 --no-push-image 标志替换为 --push-image 以在构建后自动推送镜像。

4. 在流水线中使用组件

最后,您可以在流水线中使用此组件

# pipeline.py
from kfp import compiler, dsl
from src.my_component import add

@dsl.pipeline
def addition_pipeline(x: int, y: int) -> int:
    task1 = add(a=x, b=y)
    task2 = add(a=task1.output, b=x)
    return task2.output

compiler.Compiler().compile(addition_pipeline, 'pipeline.yaml')

您的目录现在看起来像这样

pipeline.py
src/
├── my_component.py
└── math_utils.py

由于 addtarget_image 使用了Google Cloud Artifact Registry(通过 gcr.io URI 指示),此处所示的流水线假定您已将镜像推送到 Google Cloud Artifact Registry,您正在Google Cloud Vertex AI Pipelines上运行您的流水线,并且您已配置IAM 权限,以便 Vertex AI Pipelines 可以从 Artifact Registry 拉取镜像。

反馈

此页面有帮助吗?