使用缓存
Kubeflow Pipelines 支持缓存以消除冗余执行并提高 pipeline 运行的效率。本页概述了 KFP 中的缓存以及如何在 pipeline 中使用它。
概览
KFP 中的缓存是一项功能,它允许您缓存组件执行的结果并在后续运行中重复使用。当为组件启用缓存时,如果组件使用相同的输入和参数再次执行(且输出仍然可用),KFP 将重用该组件的输出。
当组件执行时间很长,或者当组件使用相同的输入和参数多次执行时,缓存尤其有用。
如果任务结果是从缓存中检索的,其在 UI 中的表示将标记一个绿色的“云到箭头”图标。
如何使用缓存
KFP 中所有组件默认启用缓存。您可以通过在任务对象上调用 .set_caching_options(enable_caching=False)
来禁用组件的缓存。
from kfp import dsl
@dsl.component
def say_hello(name: str) -> str:
hello_text = f'Hello, {name}!'
print(hello_text)
return hello_text
@dsl.pipeline
def hello_pipeline(recipient: str = 'World!') -> str:
hello_task = say_hello(name=recipient)
hello_task.set_caching_options(False)
return hello_task.output
您还可以在提交 pipeline 执行时通过设置 caching
参数来为 pipeline 中的所有组件启用或禁用缓存。这将覆盖 pipeline 中所有组件的缓存设置。
from kfp.client import Client
client = Client()
client.create_run_from_pipeline_func(
hello_pipeline,
enable_caching=True, # overrides the above disabling of caching
)
--disable-execution-caching-by-default
标志默认禁用所有 pipeline 任务的缓存。
示例
kfp dsl compile --py my_pipeline.py --output my_pipeline.yaml --disable-execution-caching-by-default
您还可以使用 KFP_DISABLE_EXECUTION_CACHING_BY_DEFAULT
环境变量来设置默认缓存行为。当设置为 true
、1
或其他 truthy 值时,它将默认禁用所有 pipeline 的执行缓存。当设置为 false
或不存在时,将保持默认的缓存启用状态。
示例
KFP_DISABLE_EXECUTION_CACHING_BY_DEFAULT=true \
kfp dsl compile --py my_pipeline.py --output my_pipeline.yaml
此环境变量也适用于 Compiler().compile()
。
给定以下 pipeline 文件
@dsl.pipeline(name='my-pipeline')
def my_pipeline():
task_1 = create_dataset()
task_2 = create_dataset()
task_1.set_caching_options(False)
Compiler().compile(
pipeline_func=my_pipeline,
package_path='my_pipeline.yaml',
)
执行以下操作
KFP_DISABLE_EXECUTION_CACHING_BY_DEFAULT=true \
python my_pipeline.py
将导致 task_2
的缓存被禁用。
注意:由于 Python 在导入过程中初始化配置,因此在导入 pipeline 组件后设置 KFP_DISABLE_EXECUTION_CACHING_BY_DEFAULT
环境变量不会影响缓存行为。因此,请始终在导入任何 Kubeflow Pipelines 组件之前设置此环境变量。