mlflow.dspy
- mlflow.dspy.autolog(log_traces: bool = True, log_traces_from_compile: bool = False, log_traces_from_eval: bool = True, log_compiles: bool = False, log_evals: bool = False, disable: bool = False, silent: bool = False)[源代码]
启用(或禁用)和配置从 DSPy 到 MLflow 的自动日志记录。目前,MLflow DSPy 模块仅支持跟踪的自动日志记录。
- 参数
log_traces – 如果为
True,则使用 DSPy 模型记录跟踪。如果为False,则在推理过程中不收集任何跟踪。默认为True。log_traces_from_compile – 如果为
True,则在编译(优化)DSPy 程序时记录跟踪。如果为False,则仅从正常的模型推理中记录跟踪,并在编译时禁用。默认为False。log_traces_from_eval – 如果为
True,则在运行 DSPy 的内置评估器时,为 DSPy 模型记录跟踪。如果为False,则仅从正常的模型推理中记录跟踪,并在运行评估器时禁用。默认为True。log_compiles – 如果为
True,则在调用 Teleprompter.compile() 时记录有关优化过程的信息。log_evals – 如果为
True,则在调用 Evaluate.__call__() 时记录有关评估调用的信息。disable – 如果为
True,则禁用 DSPy 自动日志记录集成。如果为False,则启用 DSPy 自动日志记录集成。silent – 如果为
True,则在 DSPy 自动日志记录期间抑制来自 MLflow 的所有事件日志和警告。如果为False,则显示所有事件和警告。
- mlflow.dspy.load_model(model_uri, dst_path=None)[源代码]
从运行中加载 Dspy 模型。
此函数还将设置全局 dspy 设置 dspy.settings,其方式与保存的设置相同。
- 参数
model_uri –
MLflow 模型在 URI 格式中的位置。例如:
/Users/me/path/to/local/modelrelative/path/to/local/models3://my_bucket/path/to/modelruns:/<mlflow_run_id>/run-relative/path/to/modelmlflow-artifacts:/path/to/model
有关支持的 URI 方案的更多信息,请参阅 引用 Artifacts。
dst_path – 用于下载模型工件的本地文件系统路径。如果提供了该目录,则该目录必须已存在。如果未指定,将创建一个本地输出路径。
- 返回
一个 dspy.module 实例,代表 dspy 模型。
- mlflow.dspy.log_model(dspy_model, artifact_path: str | None = None, task: str | None = None, model_config: dict[str, typing.Any] | None = None, code_paths: list[str] | None = None, conda_env: list[str] | str | None = None, signature: mlflow.models.signature.ModelSignature | None = None, input_example: Optional[Union[pandas.core.frame.DataFrame, numpy.ndarray, dict, list, csr_matrix, csc_matrix, str, bytes, tuple]] = None, registered_model_name: str | None = None, await_registration_for: int = 300, pip_requirements: list[str] | str | None = None, extra_pip_requirements: list[str] | str | None = None, metadata: dict[str, typing.Any] | None = None, resources: str | pathlib.Path | list[mlflow.models.resources.Resource] | None = None, prompts: list[str | Prompt] | None = None, name: str | None = None, params: dict[str, typing.Any] | None = None, tags: dict[str, typing.Any] | None = None, model_type: str | None = None, step: int = 0, model_id: str | None = None, use_dspy_model_save: bool = False)[源代码]
将 Dspy 模型以及元数据记录到 MLflow。
此方法将 Dspy 模型以及元数据(如模型签名和 conda 环境)保存到 MLflow。
- 参数
dspy_model – dspy.Module 的实例。要保存的 Dspy 模型。
artifact_path – Deprecated. Use name instead.
task – 默认为 None。模型的任务类型。目前只能是 llm/v1/chat 或 None。
model_config – 在实例化时传递给 Dspy 模块的关键字参数。
code_paths –
A list of local filesystem paths to Python file dependencies (or directories containing file dependencies). These files are prepended to the system path when the model is loaded. Files declared as dependencies for a given model should have relative imports declared from a common root path if multiple files are defined with import dependencies between them to avoid import errors when loading the model.
For a detailed explanation of
code_pathsfunctionality, recommended usage patterns and limitations, see the code_paths usage guide.conda_env –
Conda 环境的字典表示形式或本地文件系统上 conda 环境 yaml 文件的路径。如果提供,这将描述模型应在其中运行的环境。至少,它应该指定 get_default_conda_env() 中包含的依赖项。如果为
None,则会向模型添加一个由mlflow.models.infer_pip_requirements()推断的包含 pip 需求的 conda 环境。如果需求推断失败,它将回退到使用 get_default_pip_requirements。从conda_env获得的 pip 需求将写入 piprequirements.txt文件,完整的 conda 环境将写入conda.yaml。以下是 conda 环境的示例字典表示形式{ "name": "mlflow-env", "channels": ["conda-forge"], "dependencies": [ "python=3.8.15", { "pip": [ "dspy==x.y.z" ], }, ], }
signature –
一个
ModelSignature类的实例,描述模型的输入和输出。如果未指定但提供了input_example,则会根据提供的输入示例和模型自动推断签名。要禁用在提供输入示例时自动推断签名,请将signature设置为False。要手动推断模型签名,请对具有有效模型输入的(例如,省略目标列的训练数据集)和有效模型输出(例如,在训练数据集上进行的模型预测)的数据集调用infer_signature()from mlflow.models import infer_signature train = df.drop_column("target_label") predictions = ... # compute model predictions signature = infer_signature(train, predictions)
input_example – 一个或多个有效的模型输入实例。输入示例用作要馈送给模型的数据的提示。它将被转换为 Pandas DataFrame,然后使用 Pandas 的面向拆分(split-oriented)格式序列化为 json,或者转换为 numpy 数组,其中示例将通过转换为列表来序列化为 json。字节将进行 base64 编码。当
signature参数为None时,输入示例用于推断模型签名。registered_model_name – 默认为 None。如果设置,则在 registered_model_name 下创建一个模型版本,如果具有给定名称的注册模型尚不存在,则也创建一个注册模型。
await_registration_for – 默认为 mlflow.tracking._model_registry.DEFAULT_AWAIT_MAX_SLEEP_SECONDS。等待模型版本完成创建并处于
READY状态的最大秒数。默认情况下,函数等待五分钟。指定 0 或 None 以跳过等待。pip_requirements – 要么是 pip 需求字符串的可迭代对象(例如
["dspy", "-r requirements.txt", "-c constraints.txt"]),要么是本地文件系统上 pip 需求文件的字符串路径(例如"requirements.txt")。如果提供,这将描述模型应在其中运行的环境。如果为None,则由当前软件环境通过mlflow.models.infer_pip_requirements()推断默认需求列表。如果需求推断失败,它将回退到使用 get_default_pip_requirements。需求和约束都会被自动解析并写入requirements.txt和constraints.txt文件,并作为模型的一部分存储。需求也会被写入模型 conda 环境(conda.yaml)文件的pip部分。extra_pip_requirements –
要么是 pip 需求字符串的可迭代对象(例如
["pandas", "-r requirements.txt", "-c constraints.txt"]),要么是本地文件系统上 pip 需求文件的字符串路径(例如"requirements.txt")。如果提供,这将描述附加到根据用户当前软件环境自动生成的默认 pip 需求集中的额外 pip 需求。需求和约束都会被自动解析并写入requirements.txt和constraints.txt文件,并作为模型的一部分存储。需求也会被写入模型 conda 环境(conda.yaml)文件的pip部分。警告
以下参数不能同时指定
conda_envpip_requirementsextra_pip_requirements
此示例演示了如何使用
pip_requirements和extra_pip_requirements指定 pip requirements。metadata – 传递给模型并存储在 MLmodel 文件中的自定义元数据字典。
resources – 模型资源列表或包含模型所需资源列表的 resources.yaml 文件。
prompts –
与模型关联的 MLflow 提示注册表中已注册的提示 URI 列表。每个提示 URI 格式应为
prompt:/<name>/<version>。应在将提示与模型关联之前在 MLflow 提示注册表中注册这些提示。这将创建模型和提示之间的双向链接。关联的提示可以在 MLmodel 文件中存储的模型元数据中看到。从提示注册表 UI,您也可以导航到模型。
import mlflow prompt_template = "Hi, {name}! How are you doing today?" # Register a prompt in the MLflow Prompt Registry mlflow.prompts.register_prompt("my_prompt", prompt_template, description="A simple prompt") # Log a model with the registered prompt with mlflow.start_run(): model_info = mlflow.pyfunc.log_model( name=MyModel(), name="model", prompts=["prompt:/my_prompt/1"] ) print(model_info.prompts) # Output: ['prompt:/my_prompt/1'] # Load the prompt prompt = mlflow.genai.load_prompt(model_info.prompts[0])
name – 模型名称。
params – 要与模型一起记录的参数字典。
tags – 要与模型一起记录的标签字典。
model_type – 模型的类型。
step – 记录模型输出和指标的步骤
model_id – 模型的 ID。
use_dspy_model_save – 是否使用 dspy 内置的 dspy.Module.save 方法来保存 Dspy 模型。
import dspy import mlflow from mlflow.models import ModelSignature from mlflow.types.schema import ColSpec, Schema # Set up the LM. lm = dspy.LM(model="openai/gpt-4o-mini", max_tokens=250) dspy.settings.configure(lm=lm) class CoT(dspy.Module): def __init__(self): super().__init__() self.prog = dspy.ChainOfThought("question -> answer") def forward(self, question): return self.prog(question=question) dspy_model = CoT() mlflow.set_tracking_uri("http://127.0.0.1:5000") mlflow.set_experiment("test-dspy-logging") from mlflow.dspy import log_model input_schema = Schema([ColSpec("string")]) output_schema = Schema([ColSpec("string")]) signature = ModelSignature(inputs=input_schema, outputs=output_schema) with mlflow.start_run(): log_model( dspy_model, "model", input_example="what is 2 + 2?", signature=signature, )
- mlflow.dspy.save_model(model, path: str, task: str | None = None, model_config: dict[str, typing.Any] | None = None, code_paths: list[str] | None = None, mlflow_model: mlflow.models.model.Model | None = None, conda_env: list[str] | str | None = None, signature: mlflow.models.signature.ModelSignature | None = None, input_example: Optional[Union[pandas.core.frame.DataFrame, numpy.ndarray, dict, list, csr_matrix, csc_matrix, str, bytes, tuple]] = None, pip_requirements: list[str] | str | None = None, extra_pip_requirements: list[str] | str | None = None, metadata: dict[str, typing.Any] | None = None, resources: str | pathlib.Path | list[mlflow.models.resources.Resource] | None = None, use_dspy_model_save: bool = False)[源代码]
保存 Dspy 模型。
此方法将 Dspy 模型以及元数据(如模型签名和 conda 环境)保存到本地文件系统。此方法在 mlflow.dspy.log_model() 内部调用。
- 参数
model – dspy.Module 的实例。要保存的 Dspy 模型/模块。
path – 要保存 MLflow 模型的本地路径。
task – 默认为 None。模型的任务类型。目前只能是 llm/v1/chat 或 None。
model_config – 在实例化时传递给 Dspy 模块的关键字参数。
code_paths –
A list of local filesystem paths to Python file dependencies (or directories containing file dependencies). These files are prepended to the system path when the model is loaded. Files declared as dependencies for a given model should have relative imports declared from a common root path if multiple files are defined with import dependencies between them to avoid import errors when loading the model.
For a detailed explanation of
code_pathsfunctionality, recommended usage patterns and limitations, see the code_paths usage guide.mlflow_model – mlflow.models.Model 的实例,默认为 None。要向其添加 Dspy 模型元数据的 MLflow 模型配置。如果为 None,将创建一个空白实例。
conda_env –
Conda 环境的字典表示形式或本地文件系统上 conda 环境 yaml 文件的路径。如果提供,这将描述模型应在其中运行的环境。至少,它应该指定 get_default_conda_env() 中包含的依赖项。如果为
None,则会向模型添加一个由mlflow.models.infer_pip_requirements()推断的包含 pip 需求的 conda 环境。如果需求推断失败,它将回退到使用 get_default_pip_requirements。从conda_env获得的 pip 需求将写入 piprequirements.txt文件,完整的 conda 环境将写入conda.yaml。以下是 conda 环境的示例字典表示形式{ "name": "mlflow-env", "channels": ["conda-forge"], "dependencies": [ "python=3.8.15", { "pip": [ "dspy==x.y.z" ], }, ], }
signature –
一个
ModelSignature类的实例,描述模型的输入和输出。如果未指定但提供了input_example,则会根据提供的输入示例和模型自动推断签名。要禁用在提供输入示例时自动推断签名,请将signature设置为False。要手动推断模型签名,请对具有有效模型输入的(例如,省略目标列的训练数据集)和有效模型输出(例如,在训练数据集上进行的模型预测)的数据集调用infer_signature()from mlflow.models import infer_signature train = df.drop_column("target_label") predictions = ... # compute model predictions signature = infer_signature(train, predictions)
input_example – 一个或多个有效的模型输入实例。输入示例用作要馈送给模型的数据的提示。它将被转换为 Pandas DataFrame,然后使用 Pandas 的面向拆分(split-oriented)格式序列化为 json,或者转换为 numpy 数组,其中示例将通过转换为列表来序列化为 json。字节将进行 base64 编码。当
signature参数为None时,输入示例用于推断模型签名。pip_requirements – 要么是 pip 需求字符串的可迭代对象(例如
["dspy", "-r requirements.txt", "-c constraints.txt"]),要么是本地文件系统上 pip 需求文件的字符串路径(例如"requirements.txt")。如果提供,这将描述模型应在其中运行的环境。如果为None,则由当前软件环境通过mlflow.models.infer_pip_requirements()推断默认需求列表。如果需求推断失败,它将回退到使用 get_default_pip_requirements。需求和约束都会被自动解析并写入requirements.txt和constraints.txt文件,并作为模型的一部分存储。需求也会被写入模型 conda 环境(conda.yaml)文件的pip部分。extra_pip_requirements –
要么是 pip 需求字符串的可迭代对象(例如
["pandas", "-r requirements.txt", "-c constraints.txt"]),要么是本地文件系统上 pip 需求文件的字符串路径(例如"requirements.txt")。如果提供,这将描述附加到根据用户当前软件环境自动生成的默认 pip 需求集中的额外 pip 需求。需求和约束都会被自动解析并写入requirements.txt和constraints.txt文件,并作为模型的一部分存储。需求也会被写入模型 conda 环境(conda.yaml)文件的pip部分。警告
以下参数不能同时指定
conda_envpip_requirementsextra_pip_requirements
此示例演示了如何使用
pip_requirements和extra_pip_requirements指定 pip requirements。metadata – 传递给模型并存储在 MLmodel 文件中的自定义元数据字典。
resources – 模型资源列表或包含模型所需资源列表的 resources.yaml 文件。
use_dspy_model_save – 是否使用 dspy 内置的 dspy.Module.save 方法来保存 Dspy 模型。