使用通过 MLflow 记录的模型来跟踪和比较模型

MLflow 记录的模型可帮助你跟踪模型的整个生命周期中的进度。 训练模型时,使用mlflow.<model-flavor>.log_model()生成LoggedModel,通过唯一ID将所有关键信息联系在一起。 若要利用其功能 LoggedModels,请开始使用 MLflow 3

对于 GenAI 应用程序,LoggedModels 可以用于创建捕获 git 提交或参数的专用对象,这些对象随后可以链接到跟踪和度量。 在深度学习和经典 ML 中, LoggedModels 由 MLflow 运行生成,这是 MLflow 中的现有概念,可视为执行模型代码的作业。 训练运行将生成模型作为输出,评估运行使用现有模型作为输入来生成指标和其他可用于评估模型性能的信息。

LoggedModel对象在整个模型的生命周期中以及不同环境中持续存在,并包含指向元数据、指标、参数以及用于生成模型的代码等工件链接。 记录的模型跟踪使你可以相互比较模型、查找性能最高的模型,并在调试期间跟踪信息。

已记录的模型也可以注册到 Unity Catalog 模型注册库,使所有 MLflow 实验和工作区关于该模型的信息得以在一个位置集中获取。 有关详细信息,请参阅 MLflow 3 的模型注册表改进

生成式 AI、深度学习和传统 ML 的模型跟踪流。

改进了生成式 AI 和深度学习模型的跟踪功能

生成式人工智能和深度学习工作流尤其受益于日志记录的模型提供的精细跟踪。

Gen AI - 统一评估和跟踪数据:

  • Gen AI 模型在评估和部署期间生成其他指标,例如审阅者反馈数据和跟踪。
  • 通过实体 LoggedModel ,可以使用单个接口查询模型生成的所有信息。

深度学习 - 高效的检查点管理:

  • 深度学习训练会创建多个检查点,这些检查点是训练期间模型状态在特定点的快照。
  • MLflow 为每个检查点创建一个单独的 LoggedModel 检查点,其中包含模型的指标和性能数据。 这样,就可以比较和评估检查点,以高效识别性能最佳的模型。

创建记录模型

若要创建记录的模型,请使用与现有 MLflow 工作负载相同的 log_model() API。 以下代码片段显示如何为生成式 AI、深度学习和传统 ML 工作流创建记录模型。

有关完整的可运行笔记本示例,请参阅 示例笔记本

生成式人工智能

以下代码片段演示如何记录 LangChain 日志代理对象。 将 log_model() 方法用于您的代理类型。

# Log the chain with MLflow, specifying its parameters
# As a new feature, the LoggedModel entity is linked to its name and params
model_info = mlflow.langchain.log_model(
  lc_model=chain,
  name="basic_chain",
  params={
    "temperature": 0.1,
    "max_tokens": 2000,
    "prompt_template": str(prompt)
  },
  model_type="agent",
  input_example={"messages": "What is MLflow?"},
)

# Inspect the LoggedModel and its properties
logged_model = mlflow.get_logged_model(model_info.model_id)
print(logged_model.model_id, logged_model.params)

启动评估作业,并通过为model_id提供唯一的LoggedModel将指标链接到已记录的模型:

# Start a run to represent the evaluation job
with mlflow.start_run() as evaluation_run:
  eval_dataset: mlflow.entities.Dataset = mlflow.data.from_pandas(
    df=eval_df,
    name="eval_dataset",
  )
  # Run the agent evaluation
  result = mlflow.evaluate(
    model=f"models:/{logged_model.model_id}",
    data=eval_dataset,
    model_type="databricks-agent"
  )
  # Log evaluation metrics and associate with agent
  mlflow.log_metrics(
    metrics=result.metrics,
    dataset=eval_dataset,
    # Specify the ID of the agent logged above
    model_id=logged_model.model_id
  )

深度学习

以下代码片段演示如何在深度学习训练期间创建记录的模型。 对你的 MLflow 模型风格使用 log_model() 方法。

# Start a run to represent the training job
with mlflow.start_run():
  # Load the training dataset with MLflow. We will link training metrics to this dataset.
  train_dataset: Dataset = mlflow.data.from_pandas(train_df, name="train")
  X_train, y_train = prepare_data(train_dataset.df)

  criterion = nn.CrossEntropyLoss()
  optimizer = torch.optim.Adam(scripted_model.parameters(), lr=0.01)

  for epoch in range(101):
    X_train, y_train = X_train.to(device), y_train.to(device)
    out = scripted_model(X_train)
    loss = criterion(out, y_train)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    # Log a checkpoint with metrics every 10 epochs
    if epoch % 10 == 0:
      # Each newly created LoggedModel checkpoint is linked with its
      # name, params, and step
      model_info = mlflow.pytorch.log_model(
        pytorch_model=scripted_model,
        name=f"torch-iris-{epoch}",
        params={
          "n_layers": 3,
          "activation": "ReLU",
          "criterion": "CrossEntropyLoss",
          "optimizer": "Adam"
        },
        step=epoch,
        input_example=X_train.numpy(),
      )
      # Log metric on training dataset at step and link to LoggedModel
      mlflow.log_metric(
        key="accuracy",
        value=compute_accuracy(scripted_model, X_train, y_train),
        step=epoch,
        model_id=model_info.model_id,
        dataset=train_dataset
      )

传统机器学习

以下代码片段显示如何记录 sklearn 模型并将指标链接到 Logged Model。 对你的 MLflow 模型风格使用 log_model() 方法。

## Log the model
model_info = mlflow.sklearn.log_model(
  sk_model=lr,
  name="elasticnet",
  params={
    "alpha": 0.5,
    "l1_ratio": 0.5,
  },
  input_example = train_x
)

# Inspect the LoggedModel and its properties
logged_model = mlflow.get_logged_model(model_info.model_id)
print(logged_model.model_id, logged_model.params)

# Evaluate the model on the training dataset and log metrics
# These metrics are now linked to the LoggedModel entity
predictions = lr.predict(train_x)
(rmse, mae, r2) = compute_metrics(train_y, predictions)
mlflow.log_metrics(
  metrics={
    "rmse": rmse,
    "r2": r2,
    "mae": mae,
  },
  model_id=logged_model.model_id,
  dataset=train_dataset
)

示例笔记本

有关演示 LoggedModels 用法的示例笔记本,请参阅以下页面:

查看模型并跟踪进度

可以在工作区 UI 中查看已记录的模型:

  1. 转到工作区中的“ 试验 ”选项卡。
  2. 选择一个试验。 然后,选择“ 模型 ”选项卡。

此页面包含与试验关联的所有记录模型及其指标、参数和项目。

模型跟踪 UI。

可以生成图表来跟踪不同运行中的指标。

模型跟踪 UI 指标图表。

搜索和筛选已记录模型

在“ 模型 ”选项卡中,可以根据记录模型的属性、参数、标记和指标搜索和筛选记录的模型。

模型跟踪用户界面搜索已记录的模型。

可以根据特定于数据集的性能筛选指标,仅返回给定数据集上具有匹配指标值的模型。 如果仅提供数据集筛选器而未提供任何指标筛选器,则返回包含这些数据集上任意指标的模型。

可以根据以下属性进行筛选:

  • model_id
  • model_name
  • status
  • artifact_uri
  • creation_time (数字)
  • last_updated_time (数字)

使用以下运算符搜索和筛选类似字符串的属性、参数和标记:

  • =!=INNOT IN

使用以下比较运算符搜索和筛选数值属性和指标,:

  • =!=><>=<=

以编程方式搜索记录模型

可以使用 MLflow API 搜索记录的模型:

## Get a Logged Model using a model_id
mlflow.get_logged_model(model_id = <my-model-id>)

## Get all Logged Models that you have access to
mlflow.search_logged_models()

## Get all Logged Models with a specific name
mlflow.search_logged_models(
  filter_string = "model_name = <my-model-name>"
)

## Get all Logged Models created within a certain time range
mlflow.search_logged_models(
  filter_string = "creation_time >= <creation_time_start> AND creation_time <= <creation_time_end>"
)

## Get all Logged Models with a specific param value
mlflow.search_logged_models(
  filter_string = "params.<param_name> = <param_value_1>"
)

## Get all Logged Models with specific tag values
mlflow.search_logged_models(
  filter_string = "tags.<tag_name> IN (<tag_value_1>, <tag_value_2>)"
)

## Get all Logged Models greater than a specific metric value on a dataset, then order by that metric value
mlflow.search_logged_models(
  filter_string = "metrics.<metric_name> >= <metric_value>",
  datasets = [
    {"dataset_name": <dataset_name>, "dataset_digest": <dataset_digest>}
  ],
  order_by = [
    {"field_name": metrics.<metric_name>, "dataset_name": <dataset_name>,"dataset_digest": <dataset_digest>}
  ]
)

有关详细信息和其他搜索参数,请参阅 MLflow 3 API 文档

按模型输入和输出进行的搜索

可以按模型 ID 搜索运行,以返回记录模型作为输入或输出的所有运行。 有关筛选器字符串语法的详细信息,请参阅 针对运行的筛选

模型跟踪用户界面搜索已记录的模型。

可以使用 MLflow API 来搜索运行记录:

## Get all Runs with a particular model as an input or output by model id
mlflow.search_runs(filter_string = "model_id = <my-model-id>")

后续步骤

若要详细了解 MLflow 3 的其他新功能,请参阅以下文章: