跳到主要内容

跟踪常见问题

入门与基本用法

问:如何开始使用 MLflow 追踪?

最简单的方法是为支持的库启用自动追踪

import mlflow
import openai

# Enable automatic tracing for OpenAI
mlflow.openai.autolog()

# Your existing code now generates traces automatically
client = openai.OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}]
)

对于自定义代码,请使用 @mlflow.trace 装饰器

@mlflow.trace
def my_function(input_data):
# Your logic here
return "processed result"

问:MLflow 追踪自动支持哪些库?

MLflow 为 20 多个流行库提供自动追踪(autolog)。请在自动追踪集成查看完整列表。

用户界面与 Jupyter 集成

问:我可以直接在 Jupyter 笔记本中查看追踪信息吗?

是的!Jupyter 集成在 MLflow 2.20 及以上版本中可用。当出现以下情况时,追踪 UI 会自动在笔记本中显示:

  1. 单元格代码生成了一个追踪
  2. 您调用了 mlflow.search_traces()
  3. 您显示了一个追踪对象
import mlflow

# Set tracking URI to your MLflow server
mlflow.set_tracking_uri("https://:5000")


@mlflow.trace
def my_function():
return "Hello World"


# Trace UI will appear automatically in the notebook
my_function()

控制显示

# Disable notebook display
mlflow.tracing.disable_notebook_display()

# Enable notebook display
mlflow.tracing.enable_notebook_display()

问:如何自定义 UI 中的请求和响应预览?

您可以使用 mlflow.update_current_trace() 来自定义追踪列表的“请求”和“响应”列中显示的内容。

@mlflow.trace
def predict(messages: list[dict]) -> str:
# Customize the request preview for long message histories
custom_preview = f'{messages[0]["content"][:10]} ... {messages[-1]["content"][:10]}'
mlflow.update_current_trace(request_preview=custom_preview)

# Your model logic here
result = process_messages(messages)

# Customize response preview
mlflow.update_current_trace(response_preview=f"Result: {result[:50]}...")
return result

生产与性能

问:我可以在生产应用中使用 MLflow 追踪吗?

是的,MLflow 追踪是稳定的,并设计用于生产环境。

在生产环境中使用 MLflow 追踪时,我们建议使用 MLflow 追踪 SDK (mlflow-tracing) 来检测您的代码/模型/代理,它具有最少的依赖项和更小的安装体积。该 SDK 专为需要高效轻量级追踪解决方案的生产环境而设计。请参阅生产监控部分了解更多详情。

问:如何启用异步追踪日志记录?

异步日志记录可以显著降低性能开销(对于典型工作负载约 80%)

import mlflow

# Enable async logging
mlflow.config.enable_async_logging()

# Traces will be logged asynchronously
with mlflow.start_span(name="foo") as span:
span.set_inputs({"a": 1})
span.set_outputs({"b": 2})

# Manually flush if needed
mlflow.flush_trace_async_logging()

配置选项

您可以使用以下环境变量来配置异步日志记录的详细行为:

环境变量描述默认值
MLFLOW_ASYNC_TRACE_LOGGING_MAX_WORKERS最大工作线程数10
MLFLOW_ASYNC_TRACE_LOGGING_MAX_QUEUE_SIZE最大排队追踪数1000
MLFLOW_ASYNC_TRACE_LOGGING_RETRY_TIMEOUT重试超时时间(秒)500

问:如何在生产环境中优化追踪大小?

MLflow 的自动追踪集成捕获了丰富的信息,这对于调试和评估模型/代理非常有帮助。然而,这是以追踪大小为代价的。例如,您可能不希望记录 RAG 应用中所有检索到的文档文本。

MLflow 支持插入自定义后处理钩子,这些钩子在将追踪数据导出到后端之前应用。这允许您通过删除不必要的数据或应用安全防护措施(如屏蔽敏感数据)来减小追踪大小。

要注册自定义钩子,请使用 mlflow.tracing.configure API。例如,以下代码会从检索器跨度输出中过滤掉文档内容,以减小追踪大小:

import mlflow
from mlflow.entities.span import Span, SpanType


# Define a custom hook that takes a span as input and mutates it in-place.
def filter_retrieval_output(span: Span):
"""Filter out the document contents from the retriever span output and only keep the document ids."""
if span.span_type == SpanType.RETRIEVAL:
documents = span.outputs.get("documents")
document_ids = [doc.id for doc in documents]
span.set_outputs({"document_ids": document_ids})


# Register the hook
mlflow.tracing.configure(span_processors=[filter_retrieval_output])

# Any traces created after the configuration will be filtered by the hook.
...

有关钩子 API 和示例的更多详细信息,请参阅脱敏安全指南

故障排除

问:我无法在 MLflow UI 中打开我的追踪。我该怎么办?

追踪可能无法在 MLflow UI 中查看有多种可能的原因:

  1. 追踪尚未完成:如果追踪仍在收集中,MLflow 无法在 UI 中显示跨度。请确保所有跨度都以“OK”或“ERROR”状态正确结束。

  2. 浏览器缓存已过时:当您将 MLflow 升级到新版本时,浏览器缓存可能包含过时的数据,从而妨碍 UI 正确显示追踪。请清除浏览器缓存(Shift+F5)并刷新页面。

  3. MLflow 服务器连接性:确保您的 MLflow 跟踪服务器正在运行且可访问。

    mlflow ui --host 0.0.0.0 --port 5000
  4. 实验权限:验证您有权访问包含该追踪的实验。

问:模型执行卡住,我的追踪一直处于“进行中”状态。

有时模型或代理会卡在长时间运行的操作或无限循环中,导致追踪一直处于“进行中”状态。

为防止这种情况,您可以使用 MLFLOW_TRACE_TIMEOUT_SECONDS 环境变量为追踪设置超时。如果追踪超过超时时间,MLflow 将自动以 ERROR 状态停止追踪并将其导出到后端,以便您可以分析跨度以识别问题。默认情况下,不设置超时。

注意

超时仅适用于 MLflow 追踪。即使追踪被停止,主程序、模型或代理仍将继续运行。

例如,以下代码将超时设置为 5 秒,并模拟 MLflow 如何处理长时间运行的操作:

import mlflow
import os
import time

# Set the timeout to 5 seconds for demonstration purposes
os.environ["MLFLOW_TRACE_TIMEOUT_SECONDS"] = "5"


# Simulate a long-running operation
@mlflow.trace
def long_running():
for _ in range(10):
child()


@mlflow.trace
def child():
time.sleep(1)


long_running()
注意

MLflow 在一个后台线程中监控追踪执行时间和是否到期。默认情况下,此检查每秒执行一次,资源消耗可以忽略不计。如果您想调整该间隔,可以设置 MLFLOW_TRACE_TIMEOUT_CHECK_INTERVAL_SECONDS 环境变量。

问:我的追踪没有出现在 MLflow UI 中。可能是什么问题?

有几个问题可能导致追踪不出现:

未设置跟踪 URI:确保您的跟踪 URI 已配置。

import mlflow

mlflow.set_tracking_uri("https://:5000") # or your server URL

未设置实验:确保您正在向正确的实验记录日志。

mlflow.set_experiment("my-tracing-experiment")

未调用 Autolog:对于支持的库,确保在使用前调用了 autolog。

mlflow.openai.autolog()  # Call before using OpenAI

多线程与并发

问:在多线程处理时,我的追踪被分成了多个追踪。如何将它们合并成一个追踪?

由于 MLflow 追踪依赖于 Python 的 ContextVar,默认情况下每个线程都有自己的追踪上下文,但通过一些额外步骤,可以为多线程应用生成单个追踪。

这是一个快速示例:

import contextvars
import mlflow
from concurrent.futures import ThreadPoolExecutor


@mlflow.trace
def worker_function(data):
# Worker logic here
return process_data(data)


@mlflow.trace
def main_function(data_list):
with ThreadPoolExecutor() as executor:
futures = []
for data in data_list:
# Copy context to worker thread
ctx = contextvars.copy_context()
futures.append(executor.submit(ctx.run, worker_function, data))

results = [future.result() for future in futures]
return results

问:MLflow 追踪是否适用于 async/await 代码?

是的,MLflow 追踪支持异步函数。@mlflow.trace 装饰器可以与异步函数无缝协作。

import asyncio
import mlflow


@mlflow.trace
async def async_function(query: str):
# Async operations are traced normally
result = await some_async_operation(query)
return result


# Usage
asyncio.run(async_function("test query"))

配置与控制

问:如何临时禁用追踪?

禁用追踪,mlflow.tracing.disable() API 将停止从 MLflow 内部收集追踪数据,并且不会将任何有关追踪的数据记录到 MLflow 跟踪服务。

启用追踪(如果它被临时禁用),mlflow.tracing.enable() API 将为被调用的已检测模型重新启用追踪功能。

import mlflow

# Disable tracing
mlflow.tracing.disable()


# Your traced functions won't generate traces
@mlflow.trace
def my_function():
return "No trace generated"


my_function()

# Re-enable tracing
mlflow.tracing.enable()

# Now traces will be generated again
my_function() # This will generate a trace

问:我可以在不修改代码的情况下为我的应用程序启用/禁用追踪吗?

是的,您可以使用环境变量和全局配置:

环境变量:设置 MLFLOW_TRACING_ENABLED=false 以禁用所有追踪。

export MLFLOW_TRACING_ENABLED=false
python your_app.py # No traces will be generated

条件追踪:使用程序化控制。

import mlflow
import os

# Only trace in development
if os.getenv("ENVIRONMENT") == "development":
mlflow.openai.autolog()

MLflow 运行集成

问:如何将追踪与 MLflow 运行关联起来?

如果在运行上下文中生成追踪,它将自动与该运行关联。

import mlflow

# Create and activate an experiment
mlflow.set_experiment("Run Associated Tracing")

# Start a new MLflow Run
with mlflow.start_run() as run:
# Traces created here are associated with the run
with mlflow.start_span(name="Run Span") as parent_span:
parent_span.set_inputs({"input": "a"})
parent_span.set_outputs({"response": "b"})

然后,您可以检索特定运行的追踪。

# Retrieve traces associated with a specific Run
traces = mlflow.search_traces(run_id=run.info.run_id)
print(traces)

数据管理

问:如何删除追踪?

您可以使用 mlflow.client.MlflowClient.delete_traces() 方法删除追踪。

from mlflow.client import MlflowClient
import time

client = MlflowClient()

# Get the current timestamp in milliseconds
current_time = int(time.time() * 1000)

# Delete traces older than a specific timestamp
deleted_count = client.delete_traces(
experiment_id="1", max_timestamp_millis=current_time, max_traces=10
)
提示

删除追踪是一个不可逆的过程。请确保在 delete_traces API 中提供的设置符合预期的删除范围。

阅读更多关于追踪删除的内容。

问:我的追踪存储在哪里?

追踪存储在您的 MLflow 跟踪后端。

本地文件系统:在本地使用 mlflow ui 时,追踪存储在 mlruns 目录中。

远程跟踪服务器:使用远程 MLflow 服务器时,追踪存储在配置的后端(数据库 + 工件存储)中。

数据库:追踪元数据存储在 MLflow 跟踪数据库中。

工件存储:大型追踪数据可能存储在工件存储中(文件系统、S3 等)。

集成与兼容性

问:MLflow 追踪是否与其他可观测性工具兼容?

是的,MLflow 追踪基于 OpenTelemetry 标准构建,可以与其他可观测性工具集成。

OpenTelemetry 导出:将追踪导出到与 OTLP 兼容的系统。

自定义导出器:为您的可观测性堆栈构建自定义集成。

标准格式:使用行业标准追踪格式以实现互操作性。

有关生产监控,请参阅生产追踪了解集成模式。

问:我可以创建自定义的手动追踪和跨度吗?

是的,MLflow 提供了全面的手动追踪功能。请参阅手动追踪指南,了解有关使用装饰器、上下文管理器和低级 API 手动创建追踪和跨度的详细信息。

获取帮助

问:我可以在哪里找到更多帮助或报告问题?

文档:从 MLflow 追踪文档开始。

GitHub 问题:在 MLflow GitHub 报告错误或请求功能。

社区:加入 MLflow Slack 社区参与讨论。

Stack Overflow:搜索或提问带有 mlflow 标签的问题。

Databricks 支持:对于托管的 MLflow 功能,请联系 Databricks 支持。


对于此处未涵盖的其他问题或疑问,请查阅 MLflow 文档或联系社区。