跳到主要内容

Sentence Transformers 和 MLflow 简介

下载此笔记本

欢迎来到我们的教程,本教程将介绍如何利用 Sentence Transformers(句子转换器)MLflow 进行高级自然语言处理和模型管理。

学习目标

  • 使用 sentence-transformers 设置句子嵌入的 pipeline(管道)。
  • 使用 MLflow 记录模型和配置。
  • 理解 MLflow 中的模型签名并将其应用于 sentence-transformers
  • 部署模型并使用 MLflow 的功能进行推理。

什么是 Sentence Transformers?

Sentence Transformers 是 Hugging Face Transformers 库的扩展,专为生成语义丰富的句子嵌入而设计。它们利用 BERT 和 RoBERTa 等模型,针对语义搜索和文本聚类等任务进行了微调,从而产生高质量的句子级嵌入。

将 MLflow 与 Sentence Transformers 集成的好处

将 MLflow 与 Sentence Transformers 结合使用,可以通过以下方式增强 NLP 项目:

  • 简化实验管理和日志记录。
  • 更好地控制模型版本和配置。
  • 确保结果和模型预测的可重复性。
  • 简化生产环境中的部署过程。

这种集成可以有效地跟踪、管理和部署 NLP 应用程序。

# Disable tokenizers warnings when constructing pipelines
%env TOKENIZERS_PARALLELISM=false

import warnings

# Disable a few less-than-useful UserWarnings from setuptools and pydantic
warnings.filterwarnings("ignore", category=UserWarning)
env: TOKENIZERS_PARALLELISM=false

设置 Sentence Embedding 的环境

通过建立核心工作环境,开始您的 Sentence Transformers 和 MLflow 之旅。

初始化的关键步骤

  • 导入必要的库:SentenceTransformermlflow
  • 初始化 "all-MiniLM-L6-v2" Sentence Transformer 模型。

模型初始化

紧凑而高效的 "all-MiniLM-L6-v2" 模型因其在生成有意义的句子嵌入方面的有效性而被选中。 在 Hugging Face Hub 上探索更多模型。

模型目的

此模型擅长将句子转换为语义丰富的嵌入,适用于各种 NLP 任务,例如语义搜索和聚类。

from sentence_transformers import SentenceTransformer

import mlflow

model = SentenceTransformer("all-MiniLM-L6-v2")

使用 MLflow 定义模型签名

定义模型签名是设置 Sentence Transformer 模型以在推理期间保持一致和预期行为的关键步骤。

签名定义的步骤

  • 准备示例句子:定义示例句子以演示模型的输入和输出格式。
  • 生成模型签名:使用 mlflow.models.infer_signature 函数以及模型的输入和输出来自动定义签名。

模型签名的重要性

  • 数据格式的清晰度:确保清楚地记录模型期望和产生的数据类型和结构。
  • 模型部署和使用:对于将模型部署到生产环境至关重要,确保模型接收到正确格式的输入并产生预期的输出。
  • 错误预防:通过强制执行一致的数据格式,有助于防止模型推理期间的错误。

注意:在推理时,List[str] 输入类型等同于 str。 MLflow flavor 使用 ColSpec[str] 定义作为输入类型。

example_sentences = ["A sentence to encode.", "Another sentence to encode."]

# Infer the signature of the custom model by providing an input example and the resultant prediction output.
# We're not including any custom inference parameters in this example, but you can include them as a third argument
# to infer_signature(), as you will see in the advanced tutorials for Sentence Transformers.
signature = mlflow.models.infer_signature(
model_input=example_sentences,
model_output=model.encode(example_sentences),
)

# Visualize the signature
signature
inputs: 
[string]
outputs: 
[Tensor('float32', (-1, 384))]
params: 
None

创建实验

我们创建一个新的 MLflow 实验,以便我们要将模型记录到的运行不会记录到默认实验,而是具有其自己的上下文相关条目。

# If you are running this tutorial in local mode, leave the next line commented out.
# Otherwise, uncomment the following line and set your tracking uri to your local or remote tracking server.

# mlflow.set_tracking_uri("http://127.0.0.1:8080")

mlflow.set_experiment("Introduction to Sentence Transformers")
<Experiment: artifact_location='file:///Users/benjamin.wilson/repos/mlflow-fork/mlflow/docs/source/llms/sentence-transformers/tutorials/quickstart/mlruns/469990615226680434', creation_time=1701280211449, experiment_id='469990615226680434', last_update_time=1701280211449, lifecycle_stage='active', name='Introduction to Sentence Transformers', tags={}>

使用 MLflow 记录 Sentence Transformer 模型

在 MLflow 中记录模型对于跟踪、版本控制和部署至关重要,需要在初始化和定义 Sentence Transformer 模型的签名之后进行。

记录模型的步骤

  • 启动 MLflow Run:使用 mlflow.start_run() 启动一个新的 run(运行),将所有日志记录操作分组在一起。
  • 记录模型:使用 mlflow.sentence_transformers.log_model 记录模型,提供模型对象、artifact path(构件路径)、签名和一个输入示例。

模型日志记录的重要性

  • 模型管理:促进从训练到部署的模型生命周期管理。
  • 可重复性和跟踪:可以跟踪模型版本并确保可重复性。
  • 易于部署:通过允许轻松部署模型以进行推理,从而简化了部署。
with mlflow.start_run():
logged_model = mlflow.sentence_transformers.log_model(
model=model,
name="sbert_model",
signature=signature,
input_example=example_sentences,
)

加载模型和测试推理

在 MLflow 中记录 Sentence Transformer 模型后,我们将演示如何加载和测试它以进行实时推理。

将模型加载为 PyFunc

  • 为什么使用 PyFunc:使用 mlflow.pyfunc.load_model 加载记录的模型,以便无缝集成到基于 Python 的服务或应用程序中。
  • 模型 URI:使用 logged_model.model_uri 准确地从 MLflow 中定位和加载模型。

进行推理测试

  • 测试句子:定义句子以测试模型的嵌入生成能力。
  • 执行预测:将模型的 predict 方法与测试句子一起使用以获得嵌入。
  • 打印嵌入长度:通过检查嵌入数组的长度来验证嵌入生成,该长度对应于每个句子表示的维度。

推理测试的重要性

  • 模型验证:确认模型在加载后的预期行为和数据处理能力。
  • 部署准备:验证模型是否已准备好实时集成到应用程序服务中。
inference_test = ["I enjoy pies of both apple and cherry.", "I prefer cookies."]

# Load our custom model by providing the uri for where the model was logged.
loaded_model_pyfunc = mlflow.pyfunc.load_model(logged_model.model_uri)

# Perform a quick test to ensure that our loaded model generates the correct output
embeddings_test = loaded_model_pyfunc.predict(inference_test)

# Verify that the output is a list of lists of floats (our expected output format)
print(f"The return structure length is: {len(embeddings_test)}")

for i, embedding in enumerate(embeddings_test):
print(f"The size of embedding {i + 1} is: {len(embeddings_test[i])}")
The return structure length is: 2
The size of embedding 1 is: 384
The size of embedding 2 is: 384

显示生成的嵌入的样本

检查嵌入的内容以验证其质量并了解模型的输出。

检查嵌入样本

  • 采样的目的:检查每个嵌入中的条目的样本,以了解模型生成的向量表示。
  • 打印嵌入样本:使用 embedding[:10] 打印每个嵌入向量的前 10 个条目,以了解模型的输出。

为什么采样很重要

  • 质量检查:采样提供了一种快速的方法来验证嵌入的质量,并确保它们是有意义且非简并的。
  • 了解模型输出:查看嵌入向量的各个部分可以直观地了解模型的输出,这对于调试和开发很有帮助。
for i, embedding in enumerate(embeddings_test):
print(f"The sample of the first 10 entries in embedding {i + 1} is: {embedding[:10]}")
The sample of the first 10 entries in embedding 1 is: [ 0.04866192 -0.03687946  0.02408808  0.03534171 -0.12739632  0.00999414
0.07135344 -0.01433522  0.04296691 -0.00654414]
The sample of the first 10 entries in embedding 2 is: [-0.03879027 -0.02373698  0.01314073  0.03589077 -0.01641303 -0.0857707
0.08282158 -0.03173266  0.04507608  0.02777079]

MLflow 中的原生模型加载以实现扩展功能

通过 MLflow 对原生模型加载的支持,探索 Sentence Transformer 功能的全部范围。

为什么要支持原生加载?

  • 访问原生功能:原生加载解锁了 Sentence Transformer 模型的所有功能,这对于高级 NLP 任务至关重要。
  • 以原生方式加载模型:使用 mlflow.sentence_transformers.load_model 加载具有其全部功能的模型,从而增强了灵活性和效率。

使用原生模型生成嵌入

  • 模型编码:利用模型的原生 encode 方法生成嵌入,从而利用了优化的功能。
  • 原生编码的重要性:原生编码确保利用模型的全部嵌入生成能力,适用于大规模或复杂的 NLP 应用程序。
# Load the saved model as a native Sentence Transformers model (unlike above, where we loaded as a generic python function)
loaded_model_native = mlflow.sentence_transformers.load_model(logged_model.model_uri)

# Use the native model to generate embeddings by calling encode() (unlike for the generic python function which uses the single entrypoint of `predict`)
native_embeddings = loaded_model_native.encode(inference_test)

for i, embedding in enumerate(native_embeddings):
print(
f"The sample of the native library encoding call for embedding {i + 1} is: {embedding[:10]}"
)
2023/11/30 15:50:24 INFO mlflow.sentence_transformers: 'runs:/eeab3c1b13594fdea13e07585b1c0596/sbert_model' resolved as 'file:///Users/benjamin.wilson/repos/mlflow-fork/mlflow/docs/source/llms/sentence-transformers/tutorials/quickstart/mlruns/469990615226680434/eeab3c1b13594fdea13e07585b1c0596/artifacts/sbert_model'
The sample of the native library encoding call for embedding 1 is: [ 0.04866192 -0.03687946  0.02408808  0.03534171 -0.12739632  0.00999414
0.07135344 -0.01433522  0.04296691 -0.00654414]
The sample of the native library encoding call for embedding 2 is: [-0.03879027 -0.02373698  0.01314073  0.03589077 -0.01641303 -0.0857707
0.08282158 -0.03173266  0.04507608  0.02777079]

结论:拥抱 Sentence Transformers 和 MLflow 的力量

在结束 Sentence Transformers 简介教程之际,我们已成功地完成了将 Sentence Transformers 库与 MLflow 集成的基础知识。 这种基础知识为自然语言处理 (NLP) 领域中更高级和专门的应用奠定了基础。

关键学习内容回顾

  1. 集成基础知识:我们介绍了使用 MLflow 加载和记录 Sentence Transformer 模型的基本步骤。 这个过程证明了在 MLflow 的生态系统中集成最先进的 NLP 工具的简单性和有效性。

  2. 签名和推理:通过创建模型签名和执行推理任务,我们展示了如何操作 Sentence Transformer 模型,确保它已为实际应用做好准备。

  3. 模型加载和预测:我们探索了两种加载模型的方式 - 作为 PyFunc 模型和使用原生 Sentence Transformers 加载机制。 这种双重方法突出了 MLflow 在适应不同模型交互方法方面的多功能性。

  4. 嵌入探索:通过生成和检查句子嵌入,我们瞥见了 transformer 模型在捕获文本语义信息方面的变革潜力。

展望未来

  • 拓展视野:虽然本教程侧重于 Sentence Transformers 和 MLflow 的基础方面,但还有许多高级应用程序等待探索。 从语义相似性分析到释义挖掘,潜在的用例非常广泛且多样。

  • 继续学习:我们强烈建议您深入研究本系列中的其他教程,这些教程更深入地研究了诸如相似性分析、语义搜索和释义挖掘等更有趣的用例。 这些教程将为您提供更广泛的理解和 Sentence Transformers 在各种 NLP 任务中的更实际的应用。

最后的想法

使用 Sentence Transformers 和 MLflow 进行 NLP 的旅程才刚刚开始。 凭借从本教程中获得的技能和见解,您已做好充分的准备来探索更复杂和令人兴奋的应用程序。 先进的 NLP 模型与 MLflow 强大的管理和部署功能的集成为语言理解及其他领域的创新和探索开辟了新的途径。

感谢您加入我们的入门之旅,我们期待看到您如何在 NLP 工作中使用这些工具和概念!