版本跟踪和 LoggedModel

使用 MLflow 版本跟踪可以创建 GenAI 应用程序的版本化表示。 版本控制提供以下优势:

  • 可重现性和可审核性。 每个应用或模型版本链接到其特定代码,例如 Git 提交哈希及其配置。
  • 有关调试的帮助。 比较模型版本之间的代码、配置、评估结果和跟踪。
  • 系统评估。 使用 mlflow.genai.evaluate() 并排比较质量评分、成本和延迟等指标。

若要创建应用或模型版本,请使用LoggedModel。 在 MLflow 中,一个LoggedModel表示 GenAI 应用程序的特定版本。 你希望评估、部署或引用的应用程序的每个不同状态都可以作为新的 LoggedModel 捕获。

本页介绍 MLflow 版本跟踪。 有关分步教程,请参阅 使用 MLflow 跟踪基于 Git 的应用程序版本

版本跟踪的方法

MLflow 提供了两种版本跟踪方法:

set_active_model

将跟踪链接到特定 LoggedModel 版本。 如果具有给定名称的模型不存在,则会自动创建一个模型。

def set_active_model(
    name: Optional[str] = None,
    model_id: Optional[str] = None
) -> ActiveModel:

参数

参数 类型 必选 Description
name str \| None 不* 模型的名称。 如果模型不存在,请创建一个新模型
model_id str \| None 不* 现有 LoggedModel 的 ID

*必须提供 namemodel_id

返回值

返回 ActiveModel 可用作上下文管理器的对象(子类 LoggedModel)。

示例用法

import mlflow

# Simple usage - creates model if it doesn't exist
mlflow.set_active_model(name="my-agent-v1.0")

# Use as context manager
with mlflow.set_active_model(name="my-agent-v2.0") as model:
    print(f"Model ID: {model.model_id}")
    # Traces within this context are linked to this model

# Use with existing model ID
mlflow.set_active_model(model_id="existing-model-id")

create_external_model

为代码和工件存储在 MLflow 外部的应用程序(例如,在 Git 中)创建新的LoggedModel

def create_external_model(
    name: Optional[str] = None,
    source_run_id: Optional[str] = None,
    tags: Optional[dict[str, str]] = None,
    params: Optional[dict[str, str]] = None,
    model_type: Optional[str] = None,
    experiment_id: Optional[str] = None,
) -> LoggedModel:

参数

参数 类型 必选 Description
name str \| None 模型名称。 如果未指定,则会生成随机名称
source_run_id str \| None 关联的运行的 ID。 如果在运行上下文中,则默认为活动运行 ID
tags dict[str, str] \| None 用于组织和筛选的键值对
params dict[str, str] \| None 模型参数和配置(必须是字符串)
model_type str \| None 用户定义的分类类型(例如“agent”、“rag-system”)
experiment_id str \| None 用来关联的试验。 如果未指定,则使用活动试验

返回值

返回一个 LoggedModel 对象,其中包含:

  • model_id:模型的唯一标识符
  • name:分配的模型名称
  • experiment_id:关联的试验 ID
  • creation_timestamp:创建模型时
  • status:模型状态(对于外部模型始终为“READY” )
  • tags:标记字典
  • params:参数字典

示例用法

import mlflow

# Basic usage
model = mlflow.create_external_model(
    name="customer-support-agent-v1.0"
)

# With full metadata
model = mlflow.create_external_model(
    name="recommendation-engine-v2.1",
    model_type="rag-agent",
    params={
        "llm_model": "gpt-4",
        "temperature": "0.7",
        "max_tokens": "1000",
        "retrieval_k": "5"
    },
    tags={
        "team": "ml-platform",
        "environment": "staging",
        "git_commit": "abc123def"
    }
)

# Within a run context
with mlflow.start_run() as run:
    model = mlflow.create_external_model(
        name="my-agent-v3.0",
        source_run_id=run.info.run_id
    )

LoggedModel 类

LoggedModel 类表示 MLflow 中的版本控制模型。

属性

资产 类型 Description
model_id str 模型的唯一标识符
name str 模型名称
experiment_id str 关联的试验 ID
creation_timestamp int 创建时间(自纪元以来的毫秒)
last_updated_timestamp int 上次更新时间(自纪元以来的毫秒)
model_type str \| None 用户定义的模型类型
source_run_id str \| None 创建此模型的运行 ID
status LoggedModelStatus 模型状态(READY、FAILED_REGISTRATION 等)
tags dict[str, str] 标记字典
params dict[str, str] 参数字典
model_uri str 用于引用模型的 URI(例如“models:/model_id”)

常见模式

使用 Git 集成进行版本跟踪

import mlflow
import subprocess

# Get current git commit
git_commit = subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip()[:8]

# Create versioned model name
model_name = f"my-app-git-{git_commit}"

# Track the version
model = mlflow.create_external_model(
    name=model_name,
    tags={"git_commit": git_commit}
)

将跟踪链接到版本

import mlflow

# Set active model - all subsequent traces will be linked
mlflow.set_active_model(name="my-agent-v1.0")

# Your application code with tracing
@mlflow.trace
def process_request(query: str):
    # This trace will be automatically linked to my-agent-v1.0
    return f"Processing: {query}"

# Run the application
result = process_request("Hello world")

生产部署

在生产环境中,使用环境变量而不是调用 set_active_model()

# Set the model ID that traces should be linked to
export MLFLOW_ACTIVE_MODEL_ID="my-agent-v1.0"

最佳做法

  1. 在模型名称中使用语义版本控制(例如,“app-v1.2.3”)

  2. 在标记中包含 git 提交,以便于跟踪

  3. 参数必须是字符串 - 转换数字和布尔值

  4. 使用model_type 对类似应用程序进行分类

  5. 在跟踪之前设置活动模型 以确保正确的链接

常见问题

参数类型无效

# Error: Parameters must be strings
# Wrong:
params = {"temperature": 0.7, "max_tokens": 1000}

# Correct:
params = {"temperature": "0.7", "max_tokens": "1000"}

后续步骤