如何使用Kedro hooks将git_sha作为参数记录到Mlflow中
问题解答
你的原有实现思路逻辑是通顺的,出现git_sha缺失的核心原因是Kedro 0.18及后续版本已经将git_sha字段从before_pipeline_run钩子的run_params参数中移除,因此无法直接从run_params里获取该值。
你可以通过以下两种方案获取git sha并记录到MLflow中:
方案1:直接调用Git接口获取(通用不依赖Kedro内部逻辑)
这是最稳定的方案,不会受Kedro版本迭代影响:
- 先安装依赖库:
pip install gitpython
- 修改你的Hook实现代码:
import git from typing import Dict, Any from kedro.framework.hooks import hook_impl import mlflow class MLflowTrackingHook: @hook_impl def before_pipeline_run(self, run_params: Dict[str, Any]) -> None: """Hook implementation to start an MLflow run with the same run_id as the Kedro pipeline run. """ mlflow.start_run(run_name=run_params["run_id"]) # 记录原有run_params mlflow.log_params(run_params) # 额外获取git_sha并记录 try: repo = git.Repo(search_parent_directories=True) git_sha = repo.head.object.hexsha mlflow.log_param("git_sha", git_sha) except Exception: # 非Git仓库场景下跳过记录,避免报错 pass
方案2:从Kedro上下文获取(无需额外安装依赖)
Kedro的上下文对象本身已经内置了git_sha属性,你可以通过另一个钩子提前获取存储:
from typing import Dict, Any from kedro.framework.hooks import hook_impl from kedro.framework.context import KedroContext import mlflow class MLflowTrackingHook: def __init__(self): self._git_sha = None @hook_impl def after_context_created(self, context: KedroContext) -> None: # 从上下文获取git_sha存储 self._git_sha = context.git_sha @hook_impl def before_pipeline_run(self, run_params: Dict[str, Any]) -> None: """Hook implementation to start an MLflow run with the same run_id as the Kedro pipeline run. """ mlflow.start_run(run_name=run_params["run_id"]) mlflow.log_params(run_params) # 记录已存储的git_sha if self._git_sha: mlflow.log_param("git_sha", self._git_sha)
注意事项
如果运行环境中没有项目的.git目录(比如打包后部署的场景),两种方法都无法获取git_sha,建议保留异常捕获逻辑避免运行中断。
内容的提问来源于stack exchange,提问作者Downforu
相关产品推荐
相关产品推荐

